我正在开发一个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 ,如果条件总是返回true,则会打开默认视频网址,因为只有在找不到youtube标签时才会打开默认视频网址。我认为Last if条件不合适,任何想法?
答案 0 :(得分:0)
您应该使用chrome.tabs.query()
代替chrome.tabs.getAllInWindow()
。如果使用空.query
对象调用queryInfo
方法,则会找到所有选项卡。
所以,你的代码应该是这样的:
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/
来测试标签的网址,因为网址可以以&#34; http&#34;或者&#34; https&#34;,或者可能附加一些查询字符串,例如&#34;?hl = en&#34;或类似物,因此使用tab[i].url == "http://www.youtube.com/"
将无法确定找到标签的绝对确定性。