我实际上是通过使用后台脚本中的localStorage
对象来尝试为我的chrome扩展程序获取持久存储空间。
以下是设置:
我有一个后台脚本和一个内容脚本。内容脚本需要从扩展名localStorage
获取/设置数据。
但是,我无法收到要发送到后台脚本的消息。
以下是后台脚本中的代码:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
console.log(sender.tab ? "from a content script:" + sender.tab.url : "from the extension");
if (request.greeting == "hello")
sendResponse({farewell: "goodbye"});
});
内容脚本:
setTimeout(function () {
chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
console.log(response.farewell);
});
}, 5000);
理想情况下,后台脚本应输出from a content script: [some url]
,内容脚本应输出goodbye
。相反,我得到以下错误:
Port: Could not establish connection. Receiving end does not exist.
感谢任何帮助/建议!
谢谢:)
编辑:清单
{
"manifest_version": 2,
"name": "Helios",
"description": "Helios chrome extension.",
"version": "0.0.1",
"permissions": [
"https://secure.flickr.com/",
"storage"
],
"background": {
"page": "background.html"
},
"browser_action": {
"default_icon": {
"19": "img/icon-19.png",
"38": "img/icon-38.png"
},
"default_title": "Helios",
"default_popup": "popup.html"
},
"content_scripts":[
{
"matches": ["*://*/*"],
"css": ["css/main.css"],
"js": [
"js/vendor/jquery-1.9.1.js",
"js/vendor/handlebars-1.0.0-rc.4.js",
"js/vendor/ember-1.0.0-rc.7.js",
"js/vendor/d3.v3.js",
"js/vendor/socket.io.min.js",
"js/templates.js",
"js/main.js"
],
"run_at": "document_end"
}
],
"web_accessible_resources": [
"img/**",
"fonts/**"
]
}
修改:Chrome版
Google Chrome 29.0.1547.65 (Official Build 220622)
OS Mac OS X
Blink 537.36 (@156661)
JavaScript V8 3.19.18.19
Flash 11.8.800.170
User Agent Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.65 Safari/537.36
答案 0 :(得分:7)
来自onMessage文档。
除非事件侦听器返回,否则此函数将变为无效 从事件监听器返回true表示您希望发送一个 异步响应(这将使消息通道保持打开状态 另一端直到调用sendResponse)。
所以你的代码应该是
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
console.log(sender.tab ? "from a content script:" + sender.tab.url : "from the extension");
if (request.greeting == "hello") {
sendResponse({farewell: "goodbye"});
return true;
}
});