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

use*_*618 10 javascript google-chrome-extension

我正在尝试将内容脚本中的消息发送到Chrome扩展程序中的后台脚本,以触发打开的丰富通知.我已经可以实现这一点,但它打破了我的扩展的其余部分.

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

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

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

的manifest.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"
  ]
}
Run Code Online (Sandbox Code Playgroud)

background.js

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

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"
}});
Run Code Online (Sandbox Code Playgroud)

use*_*618 7

问题是由于我在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();
});
Run Code Online (Sandbox Code Playgroud)