Sending message from content script to background script breaks chrome extension

ε祈祈猫儿з 提交于 2021-02-18 03:50:04

问题


I am trying to send a message from a content script to the background script in a chrome extension that triggers a rich notification to open. I can already achieve this but it breaks the rest of my extension.

In my content script I have a call to chrome.extension.sendMessage inside of which I load my extension code. This was all working fine until I added my notification code, I decided to use chrome Rich Notifications API as I would like to have buttons in my notification eventually, and I am led to believe that only the background script can open the rich notification, hence the need for messages. If I comment out the chrome.runtime.OnMessage.addListener function in background.js my extension logic loads properly again, so something about that call is conflicting with the chrome.extension.sendMessage function in inject.js.

Can anyone explain why this happens and how to fix it?

A simplified version of my code is as follows:

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"
  ]
}

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"
}});

回答1:


The problem was caused because my listener in background.js was not returning a response. So the function response of my chrome.extension.sendMessage was never being executed.

I changed my background.js to be:

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

    sendResponse();
});


来源:https://stackoverflow.com/questions/26156978/sending-message-from-content-script-to-background-script-breaks-chrome-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!