javascript - 从内容脚本向后台脚本发送消息会破坏 chrome 扩展

标签 javascript google-chrome-extension

我正在尝试将消息从内容脚本发送到 chrome 扩展中的后台脚本,该扩展会触发丰富的通知打开。我已经可以做到这一点,但它破坏了我扩展的其余部分。

在我的内容脚本中,我调用了 chrome.extension.sendMessage,我在其中加载了我的扩展代码。这一切都很好,直到我添加了我的通知代码,我决定使用 chrome Rich Notifications API,因为我最终希望在我的通知中有按钮,并且我相信只有后台脚本才能打开丰富的通知,因此消息的需要。如果我注释掉 background.js 中的 chrome.runtime.OnMessage.addListener 函数,我的扩展逻辑将再次正确加载,因此该调用的某些内容与 inject.js 中的 chrome.extension.sendMessage 函数冲突。

谁能解释为什么会发生这种情况以及如何解决?

我的代码的简化版本如下:

list .json

{
  "name": "Test",
  "version": "0.0.1",
  "manifest_version": 2,
  "description": "Test
  "permissions": [
    "notifications"
  ],
  "background": {
    "persistent": false,
    "scripts": ["background.js"]
  },
  "content_scripts": [
    {
      "matches": [
        "mywebsite/*"
      ],
      "js": [
        "inject.js",
      ]
    }
  ],
  "web_accessible_resources": [
    "notificationIcon.png"
  ]
}

background.js

chrome.runtime.onMessage.addListener(function(request, sender) {
    if (request.type == "notification")
      chrome.notifications.create('notification', request.options, function() { });
});

注入(inject).js

chrome.extension.sendMessage({}, function(response) {
    //code to initialize my extension
});

//code to send message to open notification. This will eventually move into my extension logic
chrome.runtime.sendMessage({type: "notification", options: { 
    type: "basic", 
    iconUrl: chrome.extension.getURL("icon128.png"),
    title: "Test",
    message: "Test"
}});

最佳答案

问题是因为我在 background.js 中的监听器没有返回响应。所以我的 chrome.extension.sendMessage 的函数响应从未被执行。

我将 background.js 更改为:

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.type == "worktimer-notification")
      chrome.notifications.create('worktimer-notification', request.options, function() { });

    sendResponse();
});

关于javascript - 从内容脚本向后台脚本发送消息会破坏 chrome 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26156978/

相关文章:

javascript - 尝试将数据从 firebase 写入 header 元素时,无法设置 null 的属性 'innerText'

javascript - 可以将匿名函数或对函数的引用传递给 executeScript 吗?

javascript - 注入(inject)的 iframe 和其他网页(Google、Gmail、Pdf)之间的问题

javascript - Chrome扩展修改newtab页面主体?

javascript - Chrome 扩展 : Getting the document. images.length 来自当前页面,而不是弹出窗口。 (Javascript)

javascript - 如何从 chrome 扩展的存储 api 访问多个 key

javascript - 使 jQuery Popbox 在其父级之外可见

javascript - 在 Haxe 中为 HTML 元素进行元素访问转换

javascript - 向节点添加调整大小句柄

php - 使用 implode()、join() 或 json_encode() 将 PHP 数组传递到 Javascript 数组