Chrome Extension - Find out if extension tab is open

故事扮演 提交于 2020-07-09 05:52:08

问题


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?


回答1:


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')


来源:https://stackoverflow.com/questions/60357334/chrome-extension-find-out-if-extension-tab-is-open

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!