Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

chrome extension: chrome.tabs.sendmessage is sending the message to all tabs even though tabId is specified

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!

like image 813
P. Luo Avatar asked Sep 10 '15 17:09

P. Luo


People also ask

Why does Chrome keep moving my tabs?

By default, if it's using a lot of memory, Chrome purges the contents of some background tabs from RAM to conserve system resources. When you click back onto those tabs, the browser has to reload them because they have been erased from memory.

Can Chrome cycle through tabs automatically?

Auto Refresh & Switch Tabs. Auto-refresh is an extension for Google Chrome which monitors the HTTP traffic and if a page fails to load, it auto-refreshes that page. This description specially develop to Switch to next tab & refresh next (+1) tab. The duration of Switch to next tab & refresh next (+1) tab is 20 seconds.


1 Answers

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.

like image 122
Mohammed AlBanna Avatar answered Sep 21 '22 02:09

Mohammed AlBanna