Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to add Request Headers to an iframe src request?

I understand that you can set HTTP request headers very easily when making AJAX calls in JavaScript.

However is it also possible to set custom HTTP request headers when inserting an iframe into a page via script?

<iframe src="someURL"> <!-- is there any place to set headers in this? --> 
like image 485
onlywei Avatar asked Nov 17 '12 17:11

onlywei


People also ask

Can I add custom header to HTTP request?

In the Home pane, double-click HTTP Response Headers. In the HTTP Response Headers pane, click Add... in the Actions pane. In the Add Custom HTTP Response Header dialog box, set the name and value for your custom header, and then click OK.

What does iframe src do?

The src attribute specifies the address of the document to embed in an iframe.

What can I use instead of iframe?

Use the object Tag as an Alternative to Iframe in HTML We can use the tag to display another webpage in our webpage. The object tag is an alternative to the iframe tag in HTML. We can use the tag to embed different multimedia components like image, video, audio, etc.


2 Answers

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.

var xhr = new XMLHttpRequest();  xhr.open('GET', 'page.html'); 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 MIME type of the response is preserved. So if you get an html response, the html will show in the iframe. If you requested a pdf, the browser pdf viewer will kick in for the iframe.

If this is part of a long-lived client-side app, you may want to use URL.revokeObjectURL() to avoid memory leaks.

The object URLs are also 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

like image 56
FellowMD Avatar answered Oct 15 '22 14:10

FellowMD


No, you can't. However you could set the iframe source to some kind of preload script, which uses AJAX to fetch the actual page with all the headers you want.

like image 33
Niet the Dark Absol Avatar answered Oct 15 '22 15:10

Niet the Dark Absol