Chrome 扩展程序:无法让消息传递在后台脚本和内容脚本之间正常工作
Chrome extension: can't get message passing to work between background script and content script
我本质上是试图通过使用后台脚本中的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/**"
]
}
编辑:铬版本
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
来自 onMessage 文档。
当事件侦听器返回时,此函数将变为无效,除非 从事件侦听器返回 true,以指示您希望发送 异步响应(这将使消息通道保持打开 另一端,直到调用发送响应)。
所以你的代码应该看起来像
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;
}
});
相关文章:
- 如何在弹出脚本到内容脚本之间发送消息并返回
- Firefox插件SDK:在侧边栏和主脚本之间通信对象
- 函数在两个或多个脚本之间进行访问
- 在这种特殊情况下,在PHP脚本之间传递值
- Chrome扩展:在后台页面和网站页面脚本之间进行通信的最佳方法
- 如何在Chrome扩展弹出窗口和内容脚本之间发送消息
- 从java脚本到C#的回调,C#和java脚本之间的异步编程
- 不了解插件和脚本之间的区别
- 原型:这两个脚本之间的区别
- 应用程序与 Web 视图中注入的脚本之间的通信
- 执行套件时脚本之间的超时 - 量角器非角度
- Chrome 扩展程序:无法让消息传递在后台脚本和内容脚本之间正常工作
- 在Chrome内容脚本和弹出脚本之间共享redux存储
- 带类型的<脚本>标记和不带类型的<脚本>之间的区别
- 使用jquery.on()方法处理同一元素(选项标记)的两个脚本之间的冲突
- 如何在Chrome扩展中的内容脚本之间重复使用代码
- 这些脚本之间的效率有差异吗
- 在两个独立的脚本之间共享变量
- chrome扩展中的可变范围,尤其是在背景页和内容脚本之间
- Chrome DevTools和扩展中的内容脚本之间的通信