avalanche1
avalanche1

Reputation: 3592

Chrome Extension - Find out if extension tab is open

I have set up that when I click extn icon - my extn index.html opens.
If I click the icon a second time - I don't want it to open a second tab; I want it to focus the already open tab (if it's open).

The problem is with if it's open part. Ideally, I would not want to ask for a tabs permission, as it is very intrusive. Because of this restriction I cannot iterate all the open tabs and check their urls.
I tried storing extn tab id in chrome.local.storage and checking for it when I click the extn button - but always maintaining up-to-date tab number proved to be rather difficult. The ultimate obstacle was that when Chrome is closed - it doesnt fire any type of onClose event; thus I cannot clear local storage of now obsolete extn tab id.
So, when I reopen Chrome, click extn button - it will not open the new tab because it can see the old tab id in the storage and thinks that a tab is already open.

Is there any way to achieve the result w\o the tabs permission?

Upvotes: 4

Views: 2882

Answers (1)

woxxom
woxxom

Reputation: 73856

For embedded options shown in chrome://extensions UI you can simply use chrome.runtime.openOptionsPage() which will take care of refocusing the existing tab.

To find a standalone tab of your own extension use chrome.extension.getViews() and chrome.tabs.getCurrent() invoked on the other tab's JS window to get its own "current" tab:

function getOwnTabs() {
  return Promise.all(
    chrome.extension.getViews({type: 'tab'})
      .map(view =>
        new Promise(resolve =>
          view.chrome.tabs.getCurrent(tab =>
            resolve(Object.assign(tab, {url: view.location.href}))))));
}

async function openOptions(url) {
  const ownTabs = await getOwnTabs();
  const tab = ownTabs.find(tab => tab.url.includes(url));
  if (tab) {
    chrome.tabs.update(tab.id, {active: true});
  } else {
    chrome.tabs.create({url});
  }
}

Usage:

openOptions('index.html')

Upvotes: 4

Related Questions