2013-04-02 40 views
9

我正在製作一個非常簡單的Chrome擴展程序來阻止對某些域的請求(厭倦了許多網站上緩慢的頁面加載,等待Facebook垃圾)。我的問題是關於如何有效地加載用戶指定的域列表。 Chrome documentation指出,將包含'urls'的地圖傳遞給addListener調用會更有效,而不是傳入所有請求並在我的函數中檢查它們。我該怎麼做,但使用用戶提供的域/表達式列表?Chrome擴展程序有效地阻止域

這裏是我的清單和js文件至今:

的manifest.json

{ 
    "name": "I Don't Want YOur Social Networking Junk", 
    "version": "1.0", 
    "description": "This extension let's you block (Chrome will not download) content from domains. Too many sites slow themselves down by bringing in a bunch of junk from sites like facebook. This will let you block those things.", 
    "permissions": ["webRequest", "webRequestBlocking", "http://*/*", "https://*/*"], 
    "background": { 
    "scripts": ["background.js"] 
    }, 

    "manifest_version": 2 
} 

background.js

chrome.webRequest.onBeforeRequest.addListener(
function(details) { 
    return {cancel: true}; 
}, { urls: ["*://*.facebook.com/*", "*://*.facebook.net/*"] }, ["blocking"]); 

正如你可以看到我有一對夫婦的硬編碼表達式現在在urls列表中。這就是我想從用戶可以填充的內容加載的內容。建議?

+1

爲什麼不給你的用戶一個很好的選擇頁面? http://developer.chrome.com/extensions/options.html –

回答

9

使用這樣的事情:

function blockRequest(details) { 
    return {cancel: true}; 
} 

function updateFilters(urls) { 
    if(chrome.webRequest.onBeforeRequest.hasListener(blockRequest)) 
    chrome.webRequest.onBeforeRequest.removeListener(blockRequest); 
    chrome.webRequest.onBeforeRequest.addListener(blockRequest, {urls: urls}, ['blocking']); 
} 

可以提供options page讓用戶指定域阻止(最好保存這些chrome.storage API)。在您的後臺頁面中,通過在初始化或更改設置時重新註冊偵聽器來更新篩選器。

順便說一下,當它穩定時應該使用Declarative Web Request API,因爲它效率更高並且不需要持久背景頁面。