Javascript Google Chrome扩展的Scriptish/Greasemonkey GM_setValue和GM_getValue等价物

Javascript Google Chrome扩展的Scriptish/Greasemonkey GM_setValue和GM_getValue等价物,javascript,google-chrome-extension,storage,content-script,Javascript,Google Chrome Extension,Storage,Content Script,我正在开发一个Google Chrome扩展,它基本上有两个不同的内容脚本,用于两个不同的域(比如Google.com和yahoo.com): manifest.json ... "content_scripts" : [{ "matches" : ["https://*google.com/*"], "js": ["my_google.js"], "run_at":"document_end" }, { "matches" :

我正在开发一个Google Chrome扩展,它基本上有两个不同的内容脚本,用于两个不同的域(比如Google.com和yahoo.com):

manifest.json

...
"content_scripts" : [{
        "matches" : ["https://*google.com/*"],
        "js": ["my_google.js"],
        "run_at":"document_end"  
}, {
        "matches" : ["https://*yahoo.com/*"],
        "js": ["my_yahoo.js"],
        "run_at":"document_end"  
}],

"permissions": ["storage"],  
...
我需要一个永久的(不仅仅是一个会话)存储,这两个脚本都可以在其中更新和检索一些常用的共享数据。我知道,可以这样做:

chrome.storage.local.set( { 'string1' : 'value1'}, function(){ 
    console.log("string1 with value = value1 has been added to the chrome.storage");  
    // continue with script code...
});

chrome.storage.local.get( 'string1', function (data){ 
    console.log("string1 with value = " + data['string1'] + " has been retrieved from the chrome.storage" );
    // continue with script code... 
});

chrome.storage.local.remove( 'string1', function () {
    console.log("string1 has been removed from chrome.storage") ;
    // continue with script code... 
});
现在,有趣的部分来了

是否有任何API的替代品可以像跨域chrome.storage那样工作,但对其进行同步调用?我实际上想要实现的是复制Scriptish/Greasemonkey GM_setValue和GM_getValue API的行为,而不需要更改之前在Mozilla Firefox中使用的、现在转移到Google Chrome中的两个脚本的全部代码

可选:
另外,如果能够从浏览器操作图标弹出页面popup.html(popup.js)中删除string1(或者可能清除所有存储),那就太好了


有什么想法吗?

内容脚本没有同步跨域存储机制

但是,如果您真的想获得这样一个功能,那么您可以自己实现这样一个存储,方法是维护由支持的存储的本地副本

  • 初始化:用于获取所有存储的数据并将其存储在局部变量中
  • 维护:
    • 使用事件监视更改,并在需要时更新本地副本
    • 每当使用
      GM_setValue
      (等)时,立即更新本地副本,以便在
      GM_setValue
      之后立即调用
      GM_getValue
      ,得到预期结果
  • 理想情况下,您应该推迟其他脚本的执行,直到初始化存储。如果不可能,请创建一个单独的脚本,并让它在以下位置运行:“\u document\u start”。使用这种方法,当代码的其余部分在“document_end”运行时,很可能(尽管不能保证)存储已经就绪


    还有另一种同步获取/设置存储值的方法。我强烈地、强烈地劝阻您不要使用此方法。同步
    XMLHttpRequest
    和webRequest API()可用于将数据从后台页面传送到内容脚本,反之亦然。
    发送数据很简单(例如,在URL中设置一个值),
    取回数据有点困难。您可以使用
    URL.createObjectURL
    获取数据的
    blob:
    URL,并返回
    {redirectUrl:…}
    以回复内容脚本中刚创建的URL