Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a specific page is already open in Google Chrome?

Basically, I've got a packaged web application which I'd like to be able to check as it loads if there are any other instances of the web application open, and, if so, to switch to the open instance rather than create another one.

Also, for the options page, I'd like it to be able to check if the application is open, and, if so, refresh the application page if the options page has been changed.

I've been reading the documentation about the chrome.tabs JavaScript module, but I can't work out how to make the function look for a specific tab. I don't quite understand how to look for or set the tab ID for a specific tab. I think this is how to do what I want, but if I'm barking up the wrong tree please let me know.

If anyone here can explain it better for me I'd be most thankful.

like image 558
木川 炎星 Avatar asked Dec 08 '10 06:12

木川 炎星


2 Answers

These answers while helpful - are quite old and outdated. "getAllInWindow" and "selected" are now deprecated. My code also refreshed the tab, like originally asked for. I needed it to check for internal extension pages only, so here is what my code looks like:

function goToInternalPage(targetURL) {
chrome.tabs.query({}, function(tabs) {
    for (let i = 0, tab; tab = tabs[i]; i++) {
        if (tab.url===("chrome-extension://"+ chrome.runtime.id + targetURL)) {
            chrome.tabs.reload(tab.id, {}, function(){});
            chrome.tabs.update(tab.id, {active: true});
            return;
        }
    }
    chrome.tabs.create({url: targetURL});
});

}

A general version would look like this:

function goToURL(targetURL) {
chrome.tabs.query({}, function(tabs) {
    for (let i = 0, tab; tab = tabs[i]; i++) {
        if (tab.url===targetURL) {
            chrome.tabs.reload(tab.id, {}, function(){});
            chrome.tabs.update(tab.id, {active: true});
            return;
        }
    }
    chrome.tabs.create({url: targetURL});
});

}

like image 122
Gergely Szabo Avatar answered Oct 31 '22 21:10

Gergely Szabo


Look inside the Google Mail Checker extension, which has this functionality:

function goToInbox() {
  chrome.tabs.getAllInWindow(undefined, function(tabs) {
    for (var i = 0, tab; tab = tabs[i]; i++) {
      if (tab.url && isGmailUrl(tab.url)) {
        chrome.tabs.update(tab.id, {selected: true});
        return;
      }
    }
    chrome.tabs.create({url: getGmailUrl()});
  });
}

In particular, you pass getAllInWindow the windowId (or undefined for the current window) and a function, which receives the array of Tab objects. You don't modify the properties of the tab directly; rather you pass its id to the update function in order to manipulate it.

like image 33
Josh Lee Avatar answered Oct 31 '22 22:10

Josh Lee