Javascript 如何将选项卡中的URL与URL数组';谷歌浏览器扩展
到目前为止,我有:Javascript 如何将选项卡中的URL与URL数组';谷歌浏览器扩展,javascript,google-chrome,google-chrome-extension,Javascript,Google Chrome,Google Chrome Extension,到目前为止,我有: // So we can notify users var notification = webkitNotifications.createNotification( 'icon-48.png', 'Alert!', 'abcdefghijklmnop' ); // Called when the url of a tab changes. function checkForValidUrl(tabId, cha
// So we can notify users
var notification = webkitNotifications.createNotification(
'icon-48.png',
'Alert!',
'abcdefghijklmnop'
);
// Called when the url of a tab changes.
function checkForValidUrl(tabId, changeInfo, tab) {
// Compare with a the URL
if (tab.url.indexOf('example.com') > -1) {
//then
chrome.pageAction.show(tabId);
notification.show();
}
};
// Listen for any changes to the URL of any tab.
chrome.tabs.onUpdated.addListener(checkForValidUrl);
我不想像上面那样简单地与example.com进行比较,而是想对照URL数组检查URL。我该怎么做呢?如果数组很小,您可以在它上面迭代并检查。
如果它明显更大,最好的方法是对它进行预排序,并对其进行二进制搜索
另一个选项是将数组连接到单个字符串,然后只检查此字符串中是否存在(使用
indexOf
或使用regex)相同,但要循环数组:
function checkForValidUrl(tabId, changeInfo, tab) {
for (var i = 0, iLen = urlArray.length; i < iLen; i++) {
if (tab.url.indexOf(urlArray[i]) > -1) {
chrome.pageAction.show(tabId);
notification.show();
break; // halt for loop
}
}
};
函数checkforvalidul(tabId,changeInfo,tab){
for(var i=0,iLen=urlArray.length;i-1){
chrome.pageAction.show(tabId);
notification.show();
break;//停止循环
}
}
};
另一种选择是使用正则表达式并使用
if(tab.url.match(re))
,其中re
可能类似于/example\.com | example\.org | google\.com/
@itsazzad我只需重写整个逻辑并使用tab.query即可(但可能有更好的解决方案):chrome.tabs.query({url:[“*://*.google.com/*”,“*://*.example.com/*”),active:tab.active//传递更多选项卡信息},函数(选项卡){console.log(tabs);})代码>参数:[对象]查询信息