Content script doesn't communicate with background script - chrome extension

646 views Asked by At

I'm trying to send new tab URL from background.js to content.js. The .sendMessage() performs but doesn't get to the content.js

background.js:

chrome.tabs.onUpdated.addListener(
    function (tabId, changeInfo, tab) {
        if (changeInfo.url) {
            chrome.tabs.sendMessage(tabId, {
                url: changeInfo.url
            })
        }
    }
);

content.js:

chrome.runtime.onMessage.addListener(function(request, sender, callback) {
    console.log('here');
  });

manifest.json:

{
  "manifest_version": 2,

  "name": "Url tracker",
  "description": "Track your latest visited URLs",
  "version": "0.0.1",
  "icons": {
    "16": "logo-small.png",
    "48": "logo-small.png",
    "128": "logo-small.png"
  },
  "permissions": [
    "activeTab",
    "tabs"
  ],
  "background": {
    "scripts":["background.js"],
    "persistent": false
  },
  "content_scripts": [{
    "matches": ["<all_urls>"],
    "all_frames": true,
    "js": ["content.js"]
  }]
}

1

There are 1 answers

0
wOxxOm On
  1. Content scripts run after DOMContentLoaded by default (it can be changed) but the URL is reported to onUpdated when the tab starts loading i.e. before the content script runs.

    The solution is to add a check to skip the first update because it's not needed: an instance of the content script runs in each matching web page and it already knows location.href of its page.

    if (changeInfo.url && tab.status === 'complete') {
    
  2. After you reload your extension on chrome://extensions page (or update it from the web store), all its content scripts get "orphanized" and can't receive messages.

    The solution is to re-inject them explicitly.