Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Active Window (chrome.tabs)

I've made an extension for pandora.com and when the user clicks the extension icon it opens a new tab with pandora.

When pandora is already open in a new tab and the user clicks the extension, the extension will not open a new tab but I would like it to instead change the active tab to the tab with pandora already open.

This is what I have so far in my background page:

chrome.browserAction.onClicked.addListener(function(tab) {
    var found = false;
    chrome.tabs.query({}, function (tabs) {
        for (var i = 0; i < tabs.length; i++) {
            if (tabs[i].url.search("pandora.com") > -1){
                found= true; 
            }
        }
        if (found==false){
            chrome.tabs.executeScript(null,{file: "buy.js"});
        } else {
             // Changes active tab to the tab with pandora open
        }
    });
});
like image 238
Jordan Avatar asked Feb 04 '26 08:02

Jordan


2 Answers

Seems like the selected property of the second argument of chrome.tabs.update has now been deprecated.

Using the active property is the new way to do it:

chrome.tabs.update(tabId, {active: true})

If the tab to be activated is in another window, you also need to change the active window to that window using chrome.windows.update:

chrome.windows.update(windowId, {focused: true}, (window) => {
  chrome.tabs.update(tabId, {active: true})
})
like image 179
Nikhil Sinha Avatar answered Feb 08 '26 23:02

Nikhil Sinha


UPDATE- chrome.tabs.update(tabId, {selected: true}); achieves what I needed. Here's the final code:

chrome.browserAction.onClicked.addListener(function(tab) {
    var found = false;
    var tabId;
    chrome.tabs.query({}, function (tabs) {
        for (var i = 0; i < tabs.length; i++) {
            if (tabs[i].url.search("www.pandora.com/") > -1){
                found = true;
                tabId = tabs[i].id;
            }
        }
        if (found == false){
            chrome.tabs.executeScript(null,{file: "buy.js"});
        } else {
            chrome.tabs.update(tabId, {selected: true});
        }
    });
});
like image 33
Jordan Avatar answered Feb 09 '26 00:02

Jordan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!