Chrome Runtime OnMessage侦听器事件未触发

时间:2015-07-02 18:58:46

标签: javascript google-chrome google-chrome-extension

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即使在相同的内容中也不会起作用,这是一个惊喜!

我已经使用了运行时和制表符对象以及sendMessageonMessage.addListener的每个变体。

有一件奇怪的事情是,在内容脚本中的断点上,我看到hasListener通常返回false,hasListeners在添加侦听器后返回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。

也没有注册的弹出式消息。相同的扩展包。

script\popup.js

'use strict';

console.log('\'Allo \'Allo! Popup');
// File executed, it's ready for the message
chrome.runtime.sendMessage(null, { action: "start"});

1 个答案:

答案 0 :(得分:2)

sendMessage 从不在同一上下文中触发事件。只有其他上下文才会收到该消息。

至于您的初始问题,有两种形式的sendMessageruntime.sendMessage向分机的自己的网页(来源chrome-extension://yourId/)和tabs.sendMessage发送消息将消息发送到内容脚本。有关详细信息,请参阅this question

相关问题