在 Chrome 扩展中,检测标签已经打开并切换到它,否则,创建新标签

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

在 Manifest v3 中,我检测到工具栏按钮单击我的扩展图标并从我的扩展文件夹中的 page.html 文件打开一个新选项卡。麻烦的是,每次我单击扩展程序的工具栏图标时,它每次都会打开此选项卡。我怎样才能检测到它已经打开并切换到它,如果还没有打开,则创建一个新标签?

这是我的服务工作者代码,这就是问题所在。它需要一个处理程序来检测该选项卡可能已经打开,然后将已打开的选项卡设置为活动选项卡。

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

解决方案需要添加一个 Javascript Promise,调用 chrome.tabs.get()chrome.tabs.highlight(),使用 chrome.storage 存储 tab.id,以及chrome.runtime.lastError 对现有代码的一些错误处理。

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