Chrome扩展:如果找不到特定的选项卡,则执行一些代码

Chrome extension: Execute some code if a specific tab is not found

本文关键字:执行 代码 选项 扩展 如果 找不到 Chrome      更新时间:2023-09-26

我正在开发一个chrome扩展,安装后它会遍历打开的选项卡,如果找不到所需的选项卡,我会打开一个新的选项卡。以下是我的代码:

var found = false;
chrome.tabs.getAllInWindow(null, function(tabs){
    for (var i = 0; i < tabs.length; i++) {
        var tabUrl = tabs[i].url;
        if (tabUrl == 'http://www.youtube.com') {
           chrome.tabs.update(tabs[i].id,{url:someUrl,selected:true});
           found = true;  
        }
    }
});
if (!found) {
    window.open('https://www.youtube.com/watch?v=somevideid');
}

问题是,无论是否找到youtube,not found if条件始终返回true,并且打开默认视频URL的位置,因为只有在找不到youtube选项卡时才应该打开。我认为最后如果条件不在合适的位置,知道吗?

您应该使用chrome.tabs.query()而不是chrome.tabs.getAllInWindow()。如果使用空的queryInfo对象调用.query方法,则会找到所有选项卡。

所以,你的代码应该是这样的:

chrome.tabs.query({}, function(tabs) {
    var found = false;
    for (var i=0; i < tabs.length; i++) {
        if (/https?:'/'/www'.youtube'.com/.test(tabs[i].url)) {
            found = true;
            chrome.tabs.update(tabs[i].id, {url: 'https://www.youtube.com/watch?v=somevideid', active: true});
            break; // you found it, stop searching and update the tab
        }
    }
    if (!found) chrome.tabs.create({url: 'https://www.youtube.com/watch?v=somevideid', active: true});
    // you didn't find it, create a new tab with the new url and select it
});

此外,我使用正则表达式/https?:'/'/www'.youtube'.com/来测试选项卡的url,因为url可能以"http"或"https"开头,或者可能附加了一些查询字符串,如"?hl=en"或类似的字符串,所以使用tab[i].url == "http://www.youtube.com/"不会为您提供找到选项卡的绝对确定性。