5

Is there an error in the way I'm implementing this? I'm opening a new tab and then sending a message to that tab, but then all other tabs that have a listener on them also receive the message.

In background.js:

chrome.tabs.create({url:chrome.extension.getURL("placement.html")},function(tab){
    chrome.tabs.sendMessage(tab.id, {
        "name":"name",
        "payload":payload
    });
});

In placement.js (run when placement.html is loaded):

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.name == "name") {
        payload = request.payload;
    }
});

I'm seeing that whenever a new tab gets created, the payload is sent to all tabs that have this onMessage listener. This code is relatively old, so I'm not sure if maybe something changed recently that affects the way chrome.tabs.sendMessage interprets "tab.id". Any help is appreciated!

P. Luo
  • 51
  • 1
  • 1
  • 2
  • possible duplicate of [Is Chrome extension Content Script scope shared when opening a new tab with window.open (since Chrome 45)?](http://stackoverflow.com/questions/32443547/is-chrome-extension-content-script-scope-shared-when-opening-a-new-tab-with-wind) – wOxxOm Sep 10 '15 at 17:21
  • 2
    That's a bug in Chrome 45, not yet fixed, nor even reported afaik ([my comment](https://crbug.com/507461#c20) obviously was ignored). – wOxxOm Sep 10 '15 at 17:23

1 Answers1

5

I agree with @wOxxOm, this is a bug from Chrome new version...and it seems chrome.tabs.connect doesn't respect the tab id parameter.

I solved that by sending the URL of needed tab to content script and make sure the URLs are match.

From popup:

chrome.tabs.query({currentWindow: true,active: true}, function(tabs){ 
        port = chrome.tabs.connect(tabs[0].id,{name: "channelName"});
        port.postMessage({url:tabs[0].url});
});

From content script:

chrome.runtime.onConnect.addListener(function(port) {
        if(port.name == "channelName"){
        port.onMessage.addListener(function(response) {
            if(response.url == window.location.href){

            }
        }); 
    }
});

I've opened an issue here after contacted a developer from Google.

Mohammed AlBanna
  • 2,350
  • 22
  • 25