简体   繁体   中英

Chrome Extension postMessage from background script to content script every time in change crome tabs

Good day.

I have a problem sending messages from backgrouns script to content script. I try to send messages every time a user switches between browser tabs.

I get this error. Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.

Below is the code for the extension itself.

Background Script:

chrome.tabs.onActivated.addListener(function changeTab(activeInfo) {

    var port = chrome.tabs.connect(activeInfo.tabId);
    console.log(port);
    port.postMessage({tabId: activeInfo.tabId});

});

Content Script:

chrome.runtime.onConnect.addListener(function(port) {
    console.log(11111111);
    port.onMessage.addListener(function(msg) {
        console.log(22222222);
        if(msg == undefined || Object.keys(msg).length == 0) return;
        if(msg.checkExtensionRBPopup)
            port.postMessage({active: window.localStorage.getItem('extension_rb_popup')});
    });
});

Manifest:

{
  "manifest_version": 2,
  "name": "Rebatemango Extension",
  "description": "Rebatemango",
  "version": "1.0",
  "browser_action": {
    "default_popup": "popup.html"
  },
  "content_scripts": [
    {
      "matches": [
        "<all_urls>"
      ],
      "js": [
        "content.js",
      ]
    }
  ],
  "permissions": [
    "background",
    "tabs",
    "activeTab",
    "declarativeContent",
    "storage",
    "clipboardWrite",
    "cookies",
    "tabCapture",
    "displaySource",
    "webNavigation"
  ],
  "background": {
    "scripts": [
      "js/jquery.js",
      "js/libs.js",
      "background.js"
    ],
    "persistent": false
  },
  "icons": {
    "16": "images/mango.png",
    "48": "images/mango.png",
    "128": "images/mango.png"
  }
}

Please tell me what am I doing wrong? How to fix or track this error?

Your content script is using port.postMessage but there is no listener on the other side of the port in the background script, which is why the error is shown.

Solution:

Use simple messaging . Don't use ports, it's not needed here and your implementation is causing a memory leak since it creates a new port each time without releasing it. The simple messaging will handle this automatically.

chrome.tabs.sendMessage(activeInfo.tabId, {foo: 1}, response => {
  if (chrome.runtime.lastError) return;
  console.log(response);
});

The content script listener:

chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
  console.log(msg);
  sendResponse({bar: 2});
});

Other causes.

The error message may also appear if there is no content script running at the exact moment the message was sent. It may happen because by default content scripts run after DOMContentLoaded event in the web page. Or maybe the tab contained an unsupported URL like chrome:// or chrome-extension:// from an extension page or https://chrome.google.com/webstore/ or any URL forbidden by the runtime_blocked_hosts policy. For the first problem you can add "run_at": "document_start" to your content script declaration in manifest.json. For the other cases there's nothing you can do except for suppressing and ignoring the error message.

Also the background script sends {tabId: activeInfo.tabId} but onMessage listener in the content script doesn't read it. Instead it reads msg.checkExtensionRBPopup which doesn't make any sense in case it's not a copypaste artifact of posting the question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM