admin管理员组

文章数量:1429735

I want to create a Chrome Extension that can send AJAX calls with XMLHttpRequest. The website that I send the request to it not mine.

When the website gets AJAX call, it check the Referer header of the request. If I send the AJAX from my background-page (Chrome Extension) no Referer header sends, and the request denied.

How can I change the Referer header from the background-page?

I want to create a Chrome Extension that can send AJAX calls with XMLHttpRequest. The website that I send the request to it not mine.

When the website gets AJAX call, it check the Referer header of the request. If I send the AJAX from my background-page (Chrome Extension) no Referer header sends, and the request denied.

How can I change the Referer header from the background-page?

Share Improve this question asked Aug 20, 2014 at 12:28 nrofisnrofis 9,79616 gold badges69 silver badges123 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

You should be able to intercept your own request with webRequest API and modify request headers.

Specifically, listen to chrome.webRequest.onBeforeSendHeaders in a blocking manner, edit the headers object, and return it to override headers.

Not all headers can be modified in this way, but Referer can.

As stated in Xan's answer, you need to use the webRequest API. Since I love minimal examples in answers, here is one:

manifest.json permissions need to contain:

"permissions": [
    "*://target.site/", 
    "webRequest",
    "webRequestBlocking"
]

The js code to modify requests to contain an arbitrary referer:

callback = function(details) {
    details.requestHeaders.push({
        name: 'Referer',
        value: 'http://your.arbitrary.referer'
    });
    return {
        requestHeaders: details.requestHeaders
    };
};

filter = { urls: ["*://target.site/target.html"] };
opts = ['blocking', 'requestHeaders']
chrome.webRequest.onBeforeSendHeaders.addListener(callback, filter, opts);

Whenever the browser makes a request to *://target.site/target.html now, the referer will be set to http://your.arbitrary.referer. This takes effect for requests done by the user (by clicking on links or being on a site that performs AJAX-requests) as well as AJAX-requests by your own extension.

本文标签: javascriptSending AJAX from Chrome ExtensionStack Overflow