views:

3298

answers:

3

Hi, I have the following requirement. On my html page, While clicking the link of an Image ("img") or anchor("a") tags , I would like to add my 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.

Regards, Srinivas

+2  A: 

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).

Hank Gay
+6  A: 

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

Mehrdad Afshari
+1. Even when using XMLHttpRequest, setting headers isn't wholly reliable. Go for parameters.
bobince
+1  A: 

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.

AnthonyWJones