[英]How to make a variable in content script which is accessible on all the pages
I have a content script in which there is a script called myscript.js, now I have made it in such a way that if a page on google.com loads then setA of modifications are done otherwise setB of modifications are done. 我有一个内容脚本,其中有一个名为myscript.js的脚本,现在,我将其编写为:如果加载google.com上的页面,则完成setA修改,否则完成setB修改。 Now I want a variable which is accessible from all the webpages that open on that browser.
现在,我想要一个可从该浏览器上打开的所有网页访问的变量。 like we have static variables in java, the same variable is accessible to all the objects of the class, using that analogy here the static variable is the global variable and objects are webpages that load
就像我们在Java中有静态变量一样,该类的所有对象都可以访问相同的变量,在这种情况下,静态变量是全局变量,而对象是加载的网页
If you need something available in every instance of content scrips (and other extension pages too), you can use chrome.storage
API . 如果您需要在内容脚本的每个实例(以及其他扩展页面)中都可用,则可以使用
chrome.storage
API 。
A slight downside is that the API is asynchronous: 缺点是该API是异步的:
var myValue;
chrome.storage.local.get({myKey: "myDefault"}, function(data) {
myValue = data["myKey"];
// You can use myValue here..
});
// ..but not here
This is fine if you're okay with chaining asynchronous code; 如果您可以链接异步代码,这很好。 otherwise, you can maintain a local copy and update it on
onChanged
instead of using get
every time: 否则,您可以维护本地副本并在
onChanged
对其进行更新,而不是每次都使用get
:
chrome.storage.onChanged.addListener(function(changes, area) {
if(area == "local" && changes["myKey"]) {
myValue = changes["myKey"].newValue;
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.