Chrome extension: webRequest.onBeforeSendHeaders behaves strangely

I am trying to add the "Referer" -HTTP-Header to some AJAX requests in my Chrome extension. You cannot change it directly in an AJAX request, so I tried changing it using the webRequest api :

chrome.webRequest.onBeforeSendHeaders.addListener(function(data) { console.log("onBeforeSendHeaders fired"); var xdata=data.requestHeaders; xdata.push({ "name":"Referer", "value": "http://the.new/referrer" }) return {requestHeaders: xdata}; }, { //Filter urls: ["<all_urls>"], //For testing purposes types: ["xmlhttprequest"] },["requestHeaders","blocking"]); 

But this does not work for AJAX requests in my extension. It fires the event only in other AJAX requests, but not in my extension.
Another strange thing: everything works fine when the “lock” flag is not set, but I can’t change the headers.

Does anyone know a way to solve this problem (or another way to achieve my goal: change "Referer" to a site request and get the content)

Thanks:)

+4
source share
4 answers

The reason you can’t set the Referrer header when you don’t have a lock request is because the request has already left a long time ago - you are notified asynchronously and you can’t change anything about the request.

To change the headers, I use this code:

 function mod_headers(header_array,p_name,p_value) { var did_set = false; for(var i in header_array) { var header = header_array[i]; var name = header.name; var value = header.value; // If the header is already present, change it: if(name == p_name) { header.value = p_value; did_set = true; } } // if it is not, add it: if(!did_set) { header_array.push( { name : p_name , value : p_value } ); } } 
+1
source

Here's a working version that works in all cases (when the title bar is already installed or when it has not been set.)

 var requestFilter = { urls: ["<all_urls>"] }, extraInfoSpec = ['requestHeaders', 'blocking'], handler = function(details) { var isRefererSet = false; var headers = details.requestHeaders, blockingResponse = {}; for (var i = 0, l = headers.length; i < l; ++i) { if (headers[i].name == 'Referer') { headers[i].value = "http://your-url.com/"; isRefererSet = true; break; } } if (!isRefererSet) { headers.push({ name: "Referer", value: "http://your-url.com/" }); } blockingResponse.requestHeaders = headers; return blockingResponse; }; chrome.webRequest.onBeforeSendHeaders.addListener(handler, requestFilter, extraInfoSpec); 

Remember to add all of the following permissions to the manifest:

 "permissions": [ "webRequest", "webRequestBlocking", "<all_urls>" ] 
+2
source
 chrome.webRequest.onBeforeSendHeaders.addListener(function(details) { console.log(details); },{urls: ["<all_urls>"]}); 
-1
source

All Articles