Is there a way to add a custom http header into the request done by an <iframe>
when changing the source (src) using javascript?
You can make the request in javascript, setting any headers you'd like. Then you can URL. createObjectURL() , to get something suitable for the src of the iframe.
There are many uses for custom headers and they are quite commonly used. Even if you aren't using a CDN or haven't specifically defined any custom HTTP headers on your origin server, you may still be sending responses with custom headers.
Select the web site where you want to add the custom HTTP response header. In the web site pane, double-click HTTP Response Headers in the IIS section. In the actions pane, select Add. In the Name box, type the custom HTTP header name.
You can have the results of an ajax request that has custom headers be set as the content of an iframe like so:
$.ajax({ type: "GET", url: "https://app.icontact.com/icp/a/", contentType: "application/json", beforeSend: function(xhr, settings){ xhr.setRequestHeader("some_custom_header", "foo");}, success: function(data){ $("#output_iframe_id").attr('src',"data:text/html;charset=utf-8," + escape(data)) } });
This is assuming the iframe is pointing at a cross domain src. It is simpler if everything is on the same domain.
Edit: Maybe try this variation.
$.ajax({ type: "GET", url: "https://app.icontact.com/icp/a/", contentType: "application/json", beforeSend: function(xhr, settings){ xhr.setRequestHeader("some_custom_header", "foo");}, success: function(data){ $("#output_iframe_id").attr('src',"/") $("#output_iframe_id").contents().find('html').html(data); } });
Rather than using a data URI, or setting the contents to a string, you can use URL.createObjectURL()
, and set it as the src
of the iframe.
var xhr = new XMLHttpRequest(); xhr.open('GET', 'some.pdf'); xhr.onreadystatechange = handler; xhr.responseType = 'blob'; xhr.setRequestHeader('Authorization', 'Bearer ' + token); xhr.send(); function handler() { if (this.readyState === this.DONE) { if (this.status === 200) { // this.response is a Blob, because we set responseType above var data_url = URL.createObjectURL(this.response); document.querySelector('#output-frame-id').src = data_url; } else { console.error('no pdf :('); } } }
The object URLs are pretty interesting. They're of the form blob:https://your.domain/1e8def13-3817-4eab-ad8a-160923995170
. You can actually open them in a new tab and see the response, and they're discarded when the context that created them is closed.
Here's a full example: https://github.com/courajs/pdf-poc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With