Sending a message from the contents of the script to the background image of the script terminates the chrome extension

I am trying to send a message from the contents of a script to a background image of a script in a chrome extension that fires an extended notification to open. I can already achieve this, but it violates the rest of my extension.

In my script content, I have a call for chrome.extension.sendMessage, inside which I load my extension code. All this worked fine until I added the notification code, I decided to use the Chrome Rich Notifications API, since I would like to have buttons in my notification in the end, and I am convinced that only the background script can open a rich notification, therefore, the need in messages. If I comment on the chrome.runtime.OnMessage.addListener function in background.js, my extension logic will load correctly again, so something about this call contradicts the chrome.extend.sendMessage function in the inject.js file.

Can someone explain why this is happening 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"
}});
+4
1

, background.js . , response 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();
});
+3

All Articles