I am trying to add a “Referer”-HTTP-Header to certain AJAX requests in my Chrome extension.
You can’t change it directly in the AJAX request so I tried to change 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 doesn’t work for the AJAX requests in my extension. It only fires the event on other AJAX requests but not the ones done in my extension.
Another strange thing is that everything works fine when “blocking” flag is not set, but then I can’t change the headers.
Does anyone know a way to solve this (or another way to achieve my goal: changing the “Referer” for a site request and retrieving the contents)
Thank you 🙂
The reason you can’t set the Referrer header when you don’t have a blocking request is that the request has potentially already gone out – you are being notified asynchronously, and cannot change anything about the request.
To change headers, I use this code: