Let's say I have a code like this:
<img src='images/whatever.jpj' width='' height=''/>
How to configure custom headers for this request?
Will appreciate any help.
Let's say I have a code like this:
<img src='images/whatever.jpj' width='' height=''/>
How to configure custom headers for this request?
Will appreciate any help.
I'm late here, but you can do this with XMLHttpRequest
and a blob.
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob'; //so you can access the response like a normal URL
xhr.onreadystatechange = function () {
if (xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
var img = document.createElement('img');
img.src = URL.createObjectURL(xhr.response); //create <img> with src set to the blob
document.body.appendChild(img);
}
};
xhr.open('GET', 'http://images.example.com/my_secure_image.png', true);
xhr.setRequestHeader('SecretPassword', 'password123');
xhr.send();
If you want, you could check to make sure the blob's MIME type is an image.
Try (open console>networks> name: 200.jpg> RequestHeaders> hello: World!)
<img src onerror="fetch('https://picsum.photos/200',{headers: {hello:'World!'}}).then(r=>r.blob()).then(d=> this.src=window.URL.createObjectURL(d));" />
You cannot change the browser's HTTP request for resources loaded by the <img>
tag. Whatever you are trying to do, you will need to find an alternative approach.
For example, you could proxy the request through your own server and modify the headers there. Or you could parametrise the URL of the resource with a query string.
As Alex points out, you may also be able to use an XmlHTTPRequest
object to load the image data and use the setRequestHeader
function, though I suspect you are limited in what headers you can set (I doubt you can spoof the referrer or user agent for example, though I haven't tested this).
One alternative is to use cookie instead of header parameter.
If you want, for example, send a user credential to control the access to the image, this credential can be set to a cookie and this cookie can be validated at server side.
This can be done using a service worker. In your service worker, handle the fetch event, and change the mode and headers of the request:
self.addEventListener('fetch', function(event) {
const newRequest = new Request(event.request, {
headers: {"Authorization": "Bearer XXX-my-token"},
mode: "cors"
});
return fetch(newRequest);
}
It's important to change the mode from no-cors
to cors
, otherwise the header will silently be discarded.