2017-07-27 106 views
0

我正在为自己的用途创建一个扩展,但我遇到了问题。我想为background.jscontent.js分配一个变量值。尽管刷新了内容页面,但始终存在background.js的变量。这个怎么做?如何从内容脚本访问后台脚本变量

的manifest.json

{ 

    "manifest_version": 2, 
    "name": "Slownik", 
    "version": "1.0", 

    "description": "Slownik", 

    "background": { 
    "scripts": ["background.js"] 
    }, 

    "content_scripts": [ 
    { 
     "matches": ["*://*.sjp.pl/*"], 
     "js": ["content.js"] 
    } 
    ] 
} 

background.js

var test = "test"; 

content.js

test = "testA"; 

回答

3

另一种方法是使用browser.runtime.sendMessage() API。

在内容脚本:

document.addEventListener('DOMContentLoaded', function() { 
    browser.runtime.sendMessage({ 
     type: "getText" 
    }).then(function(message) { 
     console.log("Value of text is: ", message.result); 
    }); 

    browser.runtime.sendMessage({ 
     type: "setText", 
     value: "Yes, I can get you!!" 
    }).then(function(message) { 
     console.log("New value of text is: ", message.result); 
    }); 
}); 

在后台脚本:

var text = "Can you get me??"; 

browser.runtime.onMessage.addListener(function(request, sender, sendResponse) { 
    if (request.type == "getText") { 
     sendResponse({result: text}); 
    } else if (request.type == "setText") { 
     text = request.value; 
     sendResponse({result: text}); 
    } 
}); 

在浏览器控制台,我们可以看到输出:

Value of text is: Can you get me?? 
New value of text is: Yes, I can get you!! 
1

究竟是什么你的愿望是不可能的。后台脚本和内容脚本在不同的上下文中执行,在某些情况下执行不同的进程。不可能在两个环境之间直接共享一个变量。但是,您可以共享信息。

.storage.local存在能够以所有脚本均可访问的方式在您的扩展中存储信息。 存储在.storage.local中的数据在浏览器重新启动后仍然存在。您可以使用.storage.local.set(),在您的background.js中设置一个值,然后从content.js中使用.storage.local.get()获取该值。

在上面链接的MDN页面上有使用.storage.local的例子。还有很多Stack Overflow questions/answers which provide examples


1.除插入到页面上下文中的脚本。这些不是内容脚本,但可以使用内容脚本插入它们。它们是您用于访问通常在网页上运行的页面脚本中存在的变量和函数的内容。

相关问题