【问题标题】:Chrome Runtime OnMessage Listener event not firingChrome 运行时 OnMessage 侦听器事件未触发
【发布时间】:2015-07-02 18:58:46
【问题描述】:

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。

同样不注册的弹出式 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"});

【问题讨论】:

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


    【解决方案1】:

    sendMessage 从不 在相同的上下文中触发事件。只有其他上下文接收消息。

    至于您最初的问题,sendMessage 有两种形式:runtime.sendMessage 向扩展程序自己的页面发送消息(来源chrome-extension://yourId/)和tabs.sendMessage 向内容脚本发送消息。详情请见this question

    【讨论】:

    • 这绝对是有道理的。我有一个popup.js,它也发送一条消息,我将sendMessage 添加到内容脚本中只是因为这最初不适用于调试目的。使用选项卡或运行时仍然不会触发我的事件。
    • 它不会在同一页面中触发事件。
    • 对不起,我在问题的末尾添加了一些内容。我的意思是我的 popup.js 也不会触发事件,无论使用chrome.runtime.sendMessagechrome.tabs.sendMessage
    • 不,我一直在刷新以进行调试。有一次我正在使用 popup.js 中的 executeScript 函数,但遇到这些问题后又恢复了。
    猜你喜欢
    • 1970-01-01
    • 2019-01-02
    • 2013-05-19
    • 1970-01-01
    • 2020-09-06
    • 2021-01-14
    • 1970-01-01
    • 1970-01-01
    • 2014-12-02
    相关资源
    最近更新 更多