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

Javascript Chrome扩展:如果找不到特定选项卡,则执行一些代码,javascript,google-chrome,google-chrome-extension,Javascript,Google Chrome,Google Chrome Extension,我正在开发一个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.yo

我正在开发一个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');
}
var-found=false;
chrome.tabs.getAllInWindow(空,函数(制表符){
对于(变量i=0;i

问题在于,无论是否找到了youtube,如果未找到,则条件始终返回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
});
chrome.tabs.query({},函数(tabs){
var=false;
对于(变量i=0;i

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

@juvian我需要了解chrome.tabs.getAllInWindow函数的执行情况,是否在该函数中的所有代码执行后执行下一条语句?
getAllInWindow
是异步的:您正在执行匿名函数之前的最后两行。将最后两行移到匿名函数中。顺便说一句,
getAllInWindow
是。@teepeemm我想到了这一点,但该函数将为每个窗口调用多次,youtube链接可以在任何窗口中。目前我正在考虑在setTimeout函数中封装第二个if。有更好的解决方案吗?虽然答案中的代码是正确的,但您还没有解释它工作的原因。它工作的原因并不是将
chrome.tabs.getAllInWindow
替换为
chrome.tabs.query
,而是将代码放在回调函数中。OP阐明,无论函数中的代码是什么,都将使用getAllInWindow方法执行多次。因此,这不是关于if语句在代码中的位置,而是关于用于检索选项卡的正确方法,即query。如果以与getAllInWindow相同的方式多次调用
query
,则使用query而不是getAllInWindow不会解决问题。OP没有显示他们如何调用该方法,所以我们只能猜测。解决这个问题的一般和最简单的方法是使用Promise+Promise.all+
。那么,
中断
是否避免了多次执行的问题?(并不是说我对承诺一无所知。)承诺只是需要避免的。你不可能学会用承诺来为这种愚蠢的问题写好代码。。。顺便说一句@RobW nope,带有getAllInWindow的函数会被调用几次,因此for循环也会执行几次,因此中断只是在找到正确的选项卡时停止迭代,不再浪费时间搜索。