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

后端 未结 4 1606
栀梦
栀梦 2020-12-02 09:52

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 w

4条回答
  •  悲&欢浪女
    2020-12-02 10:11

    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

提交回复
热议问题