Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
387 views
in Technique[技术] by (71.8m points)

javascript - 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."

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...