最好的方法来检查Tab是否与确切的ID存在于Chrome

The best way to check if Tab with exact ID exists in Chrome

本文关键字:ID Chrome 存在 是否 方法 检查 Tab      更新时间:2023-09-26

有时选项卡Id存储在变量中,您需要在对其进行操作之前检查选项卡是否仍然存在(因为用户可以随时关闭选项卡)。我找到了这个解决方案:

chrome.tabs.get(1234567, function(tab) {
  if (typeof tab == 'undefined') {
    console.log('Tab does not exist!');
  }
});

它可以工作,但它有相当严重的缺点。它像这样将错误信息写入控制台:

Error during tabs.get: No tab with id: 1234567.

这也不例外。所以try/catch帮不上忙。这只是控制台的一条消息。

任何想法?

UPDATE:这个错误现在看起来像

Unchecked runtime.lastError while running tabs.get: No tab with id: 1234567.

function callback() {
    if (chrome.runtime.lastError) {
        console.log(chrome.runtime.lastError.message);
    } else {
        // Tab exists
    }
}
chrome.tabs.get(1234,callback);

source Chrome扩展错误:"未检查运行时。运行browserAction时发生错误。setIcon:没有id"

编辑:

Chrome检查是否检入了Chrome .runtime. lasterror的值回调,并为此"未处理的异步"输出控制台消息例外"。如果你检查它,它不会污染控制台。

来自@Xan的评论

根据Ian的评论(谢谢@Ian)有另一个解决方案。

function tabExists (tabId, onExists, onNotExists) {
  chrome.windows.getAll({ populate: true }, function (windows) {
    for (var i = 0, window; window = windows[i]; i++) {
      for (var j = 0, tab; tab = window.tabs[j]; j++) {
        if (tab.id == tabId) {
          onExists && onExists(tab);
          return;
        }
      }
    }
    onNotExists && onNotExists();
  });
}

它经过测试并且工作良好,所以每个人都可以使用它。如果有人能找到比chrome.windows.getAll更短的解决方案,请写信!

更新:由于@anglinb的答案这个我的答案是不实际的了

我很惊讶竟然没有API来完成这个简单的任务。除了@KonstantinSmolyanin上面的建议,我想出了这个更简单的方法:

function checkTabIDValid(nTabID, callbackDone)
{
    chrome.browserAction.getBadgeText({tabId: nTabID}, function(dummy)
    {
        if(callbackDone)
            callbackDone(!chrome.runtime.lastError);
    });
}

不幸的是,它还必须异步报告结果:

checkTabIDValid(tabId, function(res){
    console.log("tab " + (res ? "exists" : "doesn't exist"));
});

实际上,在chrome API中没有"exists"函数…我写了下面的代码:

  var tabID = 551;
  chrome.tabs.query(  {}, function(tabs) {
    for(let i = 0; i<tabs.length; i++){
      if (tabs[i].id === tabID) {
        alert(`Tab ${tabID} exists!`);
        return;
      }
    }
    alert(`No Tab ${tabID} here.`);
  });

前面设置一个变量
lastRemoved=tab.id;
chrome.tabs.remove(tab.id);

后面检查
chrome.tabs.onUpdated.addListener(function(tabId){
    if(lastRemoved==tabId) return;
    chrome.tabs.get(tabId,
    //...