Set custom header for the request made from <img/> tag

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.


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.


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


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));" />