Srinivas
Srinivas

Reputation: 1413

Adding custom HTTP headers using JavaScript

On an HTML page, while clicking the link of an Image ("img") or anchor ("a") tags, I would like to add custom headers for the GET request. These links are typically for downloading dynamic content. These headers could be SAML headers or custom application specific headers.

Is it possible to add these custom headers through JavaScript? Or if I add these through XMLHttpRequest, how can I achieve the download functionality?

This requirement is for IE6 or 7 only.

Upvotes: 49

Views: 169717

Answers (4)

Václav Kužel
Václav Kužel

Reputation: 1149

In 2021, this can be accomplished with Service Workers.

First, you have to register a Service Worker on your page.

// index.html
window.addEventListener('load', function () {
    navigator
        .serviceWorker
        .register('/service-worker.js');
});

In the Service Worker a request is captured, modified and forwarded by calling the WindowOrWorkerGlobalScope.fetch() method.

// service-worker.js
self.addEventListener('fetch', function (event) {
    event.respondWith(async function () {
        let headers = new Headers()
        headers.append("X-Custom-Header", "Random value")
        return fetch(event.request, {headers: headers})
    }());
});

Please note that some web browsers do not show modified requests in the developer console. In that case requests can be observed with tools like tcpdump, Wireshark or in a server's logs.

Upvotes: 5

AnthonyWJones
AnthonyWJones

Reputation: 189437

The only way to add headers to a request from inside a browser is use the XmlHttpRequest setRequestHeader method.

Using this with "GET" request will download the resource. The trick then is to access the resource in the intended way. Ostensibly you should be able to allow the GET response to be cacheable for a short period, hence navigation to a new URL or the creation of an IMG tag with a src url should use the cached response from the previous "GET". However that is quite likely to fail especially in IE which can be a bit of a law unto itself where the cache is concerned.

Ultimately I agree with Mehrdad, use of query string is easiest and most reliable method.

Another quirky alternative is use an XHR to make a request to a URL that indicates your intent to access a resource. It could respond with a session cookie which will be carried by the subsequent request for the image or link.

Upvotes: 12

Mehrdad Afshari
Mehrdad Afshari

Reputation: 421968

I think the easiest way to accomplish it is to use querystring instead of HTTP headers.

Upvotes: 13

Hank Gay
Hank Gay

Reputation: 71939

If you're using XHR, then setRequestHeader should work, e.g.

xhr.setRequestHeader('custom-header', 'value');

P.S. You should use Hijax to modify the behavior of your anchors so that it works if for some reason the AJAX isn't working for your clients (like a busted script elsewhere on the page).

Upvotes: 42

Related Questions