Konstantin Smolyanin
Konstantin Smolyanin

Reputation: 19103

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

Sometimes there is tab Id stored in a variable and you need to check if tab still exists before doing something with it (because users can close tabs at any time). I've found this solution:

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

It works but it has quite serious disadvantage. It writes error message into console like this:

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

And this is not an exception. So try/catch can't help. It's just a message in console.

Any ideas?

UPDATE: This error now looks like

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

Upvotes: 24

Views: 15621

Answers (6)

stickpin
stickpin

Reputation: 11

One more solution to check if a specific Tab ID is present:

var tabID = 111;
chrome.tabs.query({}, function(tabs) {
    if (tabs.some(tab => tabID == tab.id)) {
      // do something
    }
});

Upvotes: 1

Max Kur
Max Kur

Reputation: 46

Indeed, there is no "exists" function in chrome API... I've written this code:

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

Upvotes: 2

Konstantin Smolyanin
Konstantin Smolyanin

Reputation: 19103

There is another solution based on Ian's comment (thank you @Ian) to the question.

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

It is tested and works good so everybody can use it. If somebody can find shorter solution then using chrome.windows.getAll please write!

UPDATE: Since @anglinb's answer this my answer is not actual any more

Upvotes: 4

anglinb
anglinb

Reputation: 985

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

source Chrome Extension error: "Unchecked runtime.lastError while running browserAction.setIcon: No tab with id"

Edit:

Chrome checks if the value of chrome.runtime.lastError was checked in a callback, and outputs a console message for this "unhandled async exception". If you do check it, it won't pollute the console.

From the comment by @Xan

Upvotes: 28

c00000fd
c00000fd

Reputation: 22285

I'm quite surprised that there's no API to do this simple task. Apart from what @KonstantinSmolyanin suggested above, I came up with this simpler method:

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

Unfortunately it also has to report result asynchronously:

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

Upvotes: 2

holden321
holden321

Reputation: 1183

Set a variable before

lastRemoved=tab.id;
chrome.tabs.remove(tab.id);

And check it after

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

Upvotes: -2

Related Questions