2015-02-11 17 views
1

我一直在瀏覽谷歌瀏覽器API,以便處理擴展和與之相關的過程。我偶然發現了chrome.webRequest https://developer.chrome.com/extensions/webRequest#event-onBeforeRequest我一直在修改語法,但我迷失了它,因爲我相對較新的編程和使用鉻APIssyntaxis在保存在擴展存儲上的數組的匹配URL上

我在想什麼是使用chrome.webRequest.onBeforeRequest。 addListener(函數回調),然後使其使用chrome.tabs.remove刪除選項卡是否匹配數組,但我不知道如何做到這一點

我有這個用於刪除使用谷歌瀏覽器的選項卡匹配過濾器

var urlArray= ["*://facebook.com/*", "*://example.com/*", "*://google.com/*" ]; 
chrome.tabs.onCreated.addListener(function (tab) { 
    for (var i = 0, len = urlArray.length; i < len; i++) { 
     if (tab.url.indexOf(urlArray[i]) > -1) { 
      chrome.tabs.remove(tab.id); 
      alert("things"); 
      break; 
     } 
    } 
}); 
+0

你需要了解什麼'indexOf'一樣。 – Xan 2015-02-11 21:37:25

+0

這可能會有所幫助,如果不是重複的話:http://stackoverflow.com/questions/12433271/can-i-allow-the-extension-user-to-choose-matching-domains – Xan 2015-02-11 21:38:16

回答

0

您的代碼中的問題是,如果您檢查"*somestring*",.indexOf()函數實際上會查找確切的字符串,這意味着星號不會用作通配符,並且只會在字符串包含它們時才匹配。

下面是一個例子:

"hello".indexOf("*hello")  // -1 there's no * 
"123hello".indexOf("*hello") // -1 there's no * 
"*hello".indexOf("*hello") // 0 here it is, in the first position 
"123*hello".indexOf("*hello") // 3 and again, in the fourth position 

所以,你的情況,你應該使用Regular Expressions,像這樣:

var urlExp= /https?\:\/\/(facebook|google|example)\.com/i; 

chrome.tabs.onCreated.addListener(function (tab) { 
    if (urlExp.test(tab.url)) { 
     chrome.tabs.remove(tab.id); 
     alert("things"); 
    } 
}); 
+0

然而,我有一個問題,所以讓我們說我想關閉一個更多的網站我怎麼可以添加它,因爲你使用 var urlExp = /https?\:\/\/(facebook|google|example)\.com/i; 從我的理解只關閉手 – user4556006 2015-02-23 05:01:35

+0

@ user4556006之前建立的那些,您可以將其添加到括號中,如下所示:/https?\:\/\/(facebook|google|example|newSite)\.com/一世 – 2015-02-23 09:17:31