且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Chrome扩展程序-找出扩展程序选项卡是否打开

更新时间:2023-12-05 19:17:34

对于chrome://extensions UI中显示的嵌入式选项,您只需使用 chrome.runtime. openOptionsPage(),它将负责重新调整现有标签的位置.

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

要查找自己的扩展程序的独立标签,请使用 chrome.extension.getViews() chrome.tabs.getCurrent()在另一方调用标签的JS window以获得其自己的当前"标签:

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});
  }
}

用法:

openOptions('index.html')