简体   繁体   English

如何在所有页面上都可以访问的内容脚本中创建变量

[英]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.

相关问题 如何制作一个可以被多个页面访问的javascript变量? - How to make a javascript variable that is accessible by multiple pages? 如何使全局变量和函数可以在角度4的所有组件中访问 - how to make global variable and functions which can be accessible in all the components in angular 4 如何使 Javascript 变量只能从一个脚本标记访问? - How To Make a Javascript Variable Only Accessible From One Script Tag? 如何在Javascript中创建一个可供所有用户访问的变量? - How can I make a variable in Javascript that is accessible to all users? 如何制作一个全局可访问的变量? - How to make a globally accessible variable? 使所有文件都可以访问 winston 记录器变量 - Make winston logger variable accessible to all files Chrome扩展程序如何将我的内容脚本注入所有Facebook页面 - Chrome extension how to inject my content script into all Facebook pages 如何使所有页面中包含的可重用导航栏的文本内容反映 - How to make text content of a reusable navbar included in all pages to reflect 如何维护和访问可从所有页面访问的javascript变量? - How to maintain and access javascript variable which is accesible from all the pages? 在这种情况下如何使变量全局可访问? - How to make the variable globally accessible in this case?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM