Search code examples
javascriptgoogle-chrome-extension

In a Chrome Extension, detect tab already open and switch to it, otherwise, create new tab


In Manifest v3, I'm detecting a toolbar button click of my extension icon and opening a new tab from a page.html file in my extension folder. Trouble is, each time I click the extension's toolbar icon, it keeps opening this tab each time. How can I detect that it's already open and just switch to it, and, if not already open, create a new tab?

This is the service-worker code I have that is the problem. It needs a handler to detect that the tab might already be open and then make that already open tab as the active tab.

chrome.action.onClicked.addListener(function(tab){
  chrome.tabs.create({url: chrome.runtime.getURL('page.html'), active: true });
});

Solution

  • The solution requires adding a Javascript Promise, a call to chrome.tabs.get(), and chrome.tabs.highlight(), using chrome.storage to store the tab.id, along with some error handling on chrome.runtime.lastError to your existing code.

    chrome.action.onClicked.addListener(function(tab){
      new Promise((resolve) => {
        chrome.storage.local.get('UITabID',function(oSetting){
          resolve(oSetting.UITabID || 0);
        });
      })
      .then((nTabID) => {
        chrome.tabs.get(nTabID,function(tab){
          if (chrome.runtime.lastError) {
            chrome.tabs.create({url: chrome.runtime.getURL('page.html'), active: true },function(tab){
              chrome.storage.local.set({UITabID:tab.id});
            });
          } else {
            chrome.tabs.highlight({tabs:tab.index});
          }
        });
      });
    });