我正在开发google.com扩展,它基本上有两个不同的内容脚本,用于两个不同的域(比方说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 API可以做到这一点:
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那样工作,但是可以使用同步调用它吗?我实际上想要实现的是复制scripts /Greasemonkey GM_setValue和GM_getValue API的行为,而不需要更改以前在Mozilla中使用的、现在转移到Google的两个脚本的全部代码。
可选:
另外,能够从浏览器动作图标弹出页面- popup.html (popup.js)中删除popup.html(或者可能清除所有存储空间)也是很好的。
有什么想法吗?
发布于 2014-01-20 23:04:06
内容脚本没有同步的跨域存储机制。
但是,如果您真的想获得这样的特性,那么您可以通过维护由chrome.storage支持的存储的本地副本来实现这样的存储。
chrome.storage.local.get(null, callback)获取所有存储的数据并将其存储在局部变量中。chrome.storage.onChanged事件监视更改,并在需要时更新本地副本。GM_setValue (等)使用时,立即更新本地副本,以便在GM_setValue之后立即调用GM_setValue将提供预期的结果。
理想情况下,您应该将其他脚本的执行推迟到存储初始化之后。如果这是不可能的,创建一个单独的脚本,并让它"run_at": "document_start"。使用这种方法,当您的其余代码运行在“document_end”‘时,很可能(虽然没有保证)存储已经就绪。
还有一种同步获取/设置存储值的方法。我强烈地,强烈地劝阻您不要使用这个方法。同步XMLHttpRequest和webRequest API (chrome.webRequest.onBeforeRequest)可以用来将数据从后台页面传送到内容脚本,反之亦然。
发送数据很简单(例如在URL中设置一个值),
获取数据要困难得多。您可以使用URL.createObjectURL获取数据的blob: URL,并返回{redirectUrl: ...}来回复内容脚本中刚刚创建的URL。
https://stackoverflow.com/questions/21244944
复制相似问题