8

UPDATE
It now seems like it's only happening in the first case I described, when the Extensions tab is reloaded and a new tab is opened. Possible bug?


I'm setting up a chrome extension with a background.js page and a content-script.js.

The two communicate with each other via a port. The way it works now, the port gets intialized in the background everytime a tab gets activated or updated and the content-script listens to it via chrome.runtime.onConnect.addListener() (which returns the port).

This works fine. Except in two (similar) cases:

  1. When the extension gets reloaded in the Tools>Extensions page and a new tab is created.
  2. On the new tab page after Chrome is shutdown and restarted.

I'm have some logs that show that in these cases, background.js does initialize the port... but the content script isn't receiving it for some reason.

These are the basics of what i'm doing:

background.js

// When a tab gets activated
chrome.tabs.onActivated.addListener(function(tab) {
    port = chrome.tabs.connect(tab.tabId, { name: "fh-ext-messenger" });
    console.log(port)
    initPortListener(port);
});

// When a tab is updated
chrome.tabs.onUpdated.addListener(function(tab) {
    port = chrome.tabs.connect(tab, { name: "fh-ext-messenger" });
    console.log(port)
    initPortListener(port);
});

content.js

chrome.runtime.onConnect.addListener(function(port) {
    console.log(port);
    // ...
}

Any ideas on why this doesn't work on an initial tab?

Orry
  • 257
  • 1
  • 3
  • 10

1 Answers1

0

Content scripts are always attached to your extension. Anytime your extension is reloaded or deactivated that content script will be removed from all the tabs that it was active on.

Reloading the extension doesn't make it become active again you need to reload that particular tab.

I have also noticed that reloading the extension page reloads all extensions and shoudl explain why your previously active content scripts are not longer active.

Xiaoxin
  • 135
  • 1
  • 5
  • 5
    Content scripts are **not** removed when an extension is reloaded or deactivated. What *does* happen is that the extension API associated with the content script is invalidated. – Rob W Dec 07 '13 at 23:23
  • Have you seen this written somewhere in the documentation? – chez.mosey Apr 24 '18 at 15:26