script/contentscript.js
'use strict';
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse){
alert("hi");
return true;
});
chrome.runtime.sendMessage(null, {hello:"hello"});
我很茫然。要么addListener
没有注册回调,回调不被当发送消息解雇,或介于两者之间。我已尽我所能来限制可能的错误。sendMessage
曾经有一段时间,在popup.js
尝试了多种变体之后,我将其移植到另一台计算机上。当我拼命把sendMessage
它放在同一个文件中时,竟然发现sendMessage
即使在相同的contentscript中也无法使用,真是令人惊讶!
我用两个运行时间和标签的对象以及两者的每一个变化sendMessage
和onMessage.addListener
。
一件奇怪的事是,在内容脚本的断点上,我看到hasListener
通常hasListeners
在添加侦听器后返回false并返回true。
{
"name": "__MSG_appName__",
"version": "0.0.1",
"manifest_version": 2,
"description": "__MSG_appDescription__",
"icons": {
"16": "images/icon-16.png",
"128": "images/icon-128.png"
},
"default_locale": "en",
"content_scripts":[
{
"matches": ["http://*/*", "https://*/*"],
"js":["scripts/contentscript.js"]
}
],
"browser_action": {
"default_icon": {
"19": "images/icon-19.png",
"38": "images/icon-38.png"
},
"default_title": "pluralsight dl",
"default_popup": "popup.html"
},
"options_page": "options.html",
"permissions":[
"activeTab",
"tabs",
"http://*/*",
"https://*/*"
]
}
有什么想法为什么不起作用?两台计算机都使用版本43。
弹出的js消息也未注册。相同的扩展程序包。
script\popup.js
'use strict';
console.log('\'Allo \'Allo! Popup');
// File executed, it's ready for the message
chrome.runtime.sendMessage(null, { action: "start"});
sendMessage
永远不要在相同的上下文中触发该事件。只有其他上下文会收到该消息。
对于您的最初问题,有两种形式sendMessage
:runtime.sendMessage
将消息发送到扩展程序自己的页面(origin chrome-extension://yourId/
),以及tabs.sendMessage
将消息发送到内容脚本。有关更多详细信息,请参见此问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句