2013-03-19 91 views
11

我想在我的擴展中實現chrome.webRequest API,但由於某種原因,無論我做什麼,它都無法正常工作。有人可以發佈使用示例嗎?或糾正我的錯誤?基本上我試圖做的是從響應中截獲接收到的頭文件。chrome.webRequest不能正常工作?

這是onBeforeSendHeaders實現,但我想用OnHeadersRecieved以及 :

var requestFilter = { 
    urls: [ "<all_urls>" ] 
    }, 
    // The 'extraInfoSpec' parameter modifies how Chrome calls your 
    // listener function. 'requestHeaders' ensures that the 'details' 
    // object has a key called 'requestHeaders' containing the headers, 
    // and 'blocking' ensures that the object your function returns is 
    // used to overwrite the headers 
    extraInfoSpec = ['requestHeaders','blocking'], 
    // Chrome will call your listener function in response to every 
    // HTTP request 
    handler = function(details) { 
    alert(details); 
    var headers = details.requestHeaders, 
     blockingResponse = {}; 

    // Each header parameter is stored in an array. Since Chrome 
    // makes no guarantee about the contents/order of this array, 
    // you'll have to iterate through it to find for the 
    // 'User-Agent' element 
    for(var i = 0, l = headers.length; i < l; ++i) { 
     if(headers[i].name == 'User-Agent') { 
     headers[i].value = '>>> Your new user agent string here <<<'; 
     break; 
     } 
     // If you want to modify other headers, this is the place to 
     // do it. Either remove the 'break;' statement and add in more 
     // conditionals or use a 'switch' statement on 'headers[i].name' 
    } 

    blockingResponse.requestHeaders = headers; 
    return blockingResponse; 
    }; 

chrome.webRequest.onBeforeSendHeaders.addListener(handler, requestFilter, extraInfoSpec); 

這是我的清單文件:

{ 
    "background_page": "iRBackground.html", 
    "browser_action": { 
     "default_icon": "Off.png", 
     "popup": "iRMenu.html" 
    }, 
    "content_scripts": [ { 
     "js": [ "Content.js" ], 
     "matches": [ "http://*/*" ], 
     "run_at": "document_start" 
    } ], 
    "description": "***", 
    "icons": { 
     "128": "On128x128.png", 
     "16": "On.png", 
     "48": "On48x48.png" 
    }, 
    "key": "****", 
    "manifest_version": 2, 
    "name": "***", 
    "permissions": [ "tabs", "notifications", "unlimitedStorage", "webRequest", 「webRequestBlocking」, 「<all_urls>」], 
    "update_url": "***/Chrome/UpdateVersion.xml", 
    "version": "1.3" 
} 

我從Chrome中得到的錯誤是: Uncaught TypeError: Cannot read property 'onBeforeSendHeaders' of undefined

任何人都可以看到任何錯誤?謝謝

+0

'webRequest' API僅適用於擴展程序的進程(例如後臺/活動頁面)。 – 2013-03-19 15:07:52

+1

這段代碼寫在我的背景頁面中.. – user1326293 2013-03-19 15:16:09

+0

請給我們完整的清單 – 2013-03-19 16:10:32

回答

24

那麼對於一個用法的例子,我可以給你這個工作代碼。我是這樣寫的,因爲另一種方式似乎倒退了,但這只是我個人的偏好,他們應該都是一樣的。

清單

{ 
    "name": "Chrome webrequest test", 
    "version": "0.1", 
    "description": "A test for webrequest", 
    "manifest_version": 2, 
    "permissions": [ 
    "<all_urls>","webRequest","webRequestBlocking" 
    ], 
    "background": { 
    "scripts": ["bgp.js"], 
    "persistent": true 
    } 
} 

bgp.js

chrome.webRequest.onBeforeSendHeaders.addListener(function(details){ 
    //console.log(JSON.stringify(details)); 
    var headers = details.requestHeaders, 
    blockingResponse = {}; 

    // Each header parameter is stored in an array. Since Chrome 
    // makes no guarantee about the contents/order of this array, 
    // you'll have to iterate through it to find for the 
    // 'User-Agent' element 
    for(var i = 0, l = headers.length; i < l; ++i) { 
    if(headers[i].name == 'User-Agent') { 
     headers[i].value = '>>> Your new user agent string here <<<'; 
     console.log(headers[i].value); 
     break; 
    } 
    // If you want to modify other headers, this is the place to 
    // do it. Either remove the 'break;' statement and add in more 
    // conditionals or use a 'switch' statement on 'headers[i].name' 
    } 

    blockingResponse.requestHeaders = headers; 
    return blockingResponse; 
}, 
{urls: [ "<all_urls>" ]},['requestHeaders','blocking']); 
+1

嗨,我創建了一個文件夾與2個文件:manifest.json和bgp.js並輸入你分別給出的數據和加載這兩個作爲一個解壓擴展名。後來我嘗試了一些不起作用的代碼,但後來我嘗試在bgp.js中插入一些alert(),它不會觸發任何事情......有一個想法我做錯了什麼? – user1326293 2013-03-19 19:09:33

+0

@ user1326293這正是我所擁有的,它工作得很好。在這裏,我把這些文件放在[zip](https://dl.dropbox.com/u/12636410/webRequest.zip)中。提取它,然後再試一次。在擴展控制檯中是否有任何消息? – BeardFist 2013-03-19 19:46:07

+0

謝謝,我發現問題是我的鍍鉻版...不過你的例子幫助:)謝謝 – user1326293 2013-03-20 12:29:14

4

我只是在我的擴展解決了這個問題在這裏:https://github.com/devinrhode2/tweet-bar 我需要什麼做的是使用chrome.webRequest.onBeforeSendHeaders.addListener,但是這也意味着在webRequest, webRequestBlocking權限中加入..會更好地使用declarativeWebRequest,但是這個項目不是那個impo rtant給我。

關鍵的東西:

  • manifest.json "background": { "persistent": true,
  • "permissions": [ "webRequest", "webRequestBlocking",

當您在manifest.json的這些變化,你實際上應該考慮重新安裝擴展,以確保公正的變化正在拾起。

這是我的過濾器代碼。你的不應該是完全相同的。看到這裏的文檔https://developer.chrome.com/extensions/webRequest

chrome.webRequest.onBeforeSendHeaders.addListener((req) => { 
    console.log('onBeforeSendHeaders'); 
    req.requestHeaders.forEach(function(header, index){ 
    console.log(header.name+':', header.value); 
    if (headers[header.name.toLowerCase()]) { 
     console.log('set header:'+header.name, 'to:'+headers[header.name.toLowerCase()]); 
     req.requestHeaders[index].value = headers[header.name.toLowerCase()] 
    } 
    }) 
    return {requestHeaders: req.requestHeaders}; 
},{ 
    urls: ['https://twitter.com/i/tweet/create'], 
    types: ["xmlhttprequest"] 
},[ 
    'blocking', 
    'requestHeaders' 
]); 

我還添加了這些頭我XHR請求,不傷害,讓你看起來更類似於正常的網站:

//add headers: 
    var headers = { 
    'content-type': 'application/x-www-form-urlencoded', 
    accept: 'application/json, text/javascript, */*; q=0.01', 
    origin: 'https://twitter.com', 
    referer: 'https://twitter.com/', 
    'x-requested-with': 'XMLHttpRequest' 
    }; 
    console.log('change') 
    Object.keys(headers).forEach((header) => { 
    postXhr.setRequestHeader(header, headers[header]); 
    }) 
+1

「......實際上你應該考慮重新安裝擴展程序,以確保正在接受更改。」謝謝!重新安裝擴展程序對我來說有訣竅! – 2016-09-12 02:30:19

0

這裏是配置清單

"permissions": [ 
    "webRequestBlocking" 
    ,"webRequest" 
    ,"http://*.beibei.com/*" 
], 
"background" : { 
    "page"  : "xxx.html", 
    "persistent" : true 
} 

這裏是JavaScript的演示代碼

$(function() { 
    // add event listners 
    chrome.webRequest.onBeforeRequest.addListener(
     function(details) { 
      console.log('onBeforeRequest', details); 
     }, 
     {urls: ["http://www.beibei.com/"]}, 
     [] 
    ); 

    chrome.webRequest.onBeforeSendHeaders.addListener(
     function(details) { 
      console.log('onBeforeSendHeaders', details); 
     }, 
     {urls: ["http://www.beibei.com/"]}, 
     ["requestHeaders"] 
    ); 

    chrome.webRequest.onCompleted.addListener( 
     function(details) { 
      console.log('onCompleted', details); 
     }, 
     {urls: ["http://www.beibei.com/"]}, 
     [] 
    ); 

    // do a GET request, so that relative events will be fired, need jquery here 
    $.get('http://www.beibei.com/'); 
});