Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

chrome.runtime.onConnect.addListener() doesn't work on initial chrome tab

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?

like image 854
Orry Avatar asked Dec 04 '13 20:12

Orry


1 Answers

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.

like image 197
Xiaoxin Avatar answered Sep 26 '22 17:09

Xiaoxin