是否可以向iframe src请求添加请求标头?

时间:2012-11-17 17:16:54

标签: javascript iframe httprequest

据我所知,在JavaScript中进行AJAX调用时,您可以非常轻松地设置HTTP请求标头。

但是,通过脚本将iframe插入页面时,还可以设置自定义HTTP请求标头吗?

<iframe src="someURL"> <!-- is there any place to set headers in this? -->

4 个答案:

答案 0 :(得分:43)

您可以在javascript中发出请求,设置您想要的任何标头。然后,您可以URL.createObjectURL()获取适合iframe的df1$prop <- with(df1, ave(count, sleep, FUN=prop.table)) 的内容。

src

保留响应的MIME类型。因此,如果你得到一个html响应,html将显示在iframe中。如果您请求pdf,浏览器pdf查看器将启动iframe。

如果这是长期客户端应用程序的一部分,您可能希望使用URL.revokeObjectURL()来避免内存泄漏。

对象网址也非常有趣。它们的格式为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 :('); } } } 。您实际上可以在新选项卡中打开它们并查看响应,并在创建它们的上下文关闭时丢弃它们。

以下是一个完整的示例:https://github.com/courajs/pdf-poc

答案 1 :(得分:22)

不,你不能。但是,您可以将iframe源设置为某种预加载脚本,该脚本使用AJAX来获取包含所需标题的实际页面。

答案 2 :(得分:2)

事实证明,Chrome 71不推荐使用URL.createObjectURL()
(请参见https://developers.google.com/web/updates/2018/10/chrome-71-deps-rems
在@Niet上建立黑暗的Absol和@FellowMD的出色答案,如果需要传递身份验证标头,以下是将文件加载到iframe中的方法。 (您不能只将src属性设置为URL):

$scope.load() {
    var iframe = #angular.element("#reportViewer");
    var url = "http://your.url.com/path/etc";
    var token = "your-long-auth-token";
    var headers = [['Authorization', 'Bearer ' + token]];
    $scope.populateIframe(iframe, url, headers);
}

$scope.populateIframe = function (iframe, url, headers) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    xhr.onreadystatechange = handler;
    xhr.responseType = 'document';
    headers.forEach(function (header) {
        xhr.setRequestHeader(header[0], header[1]);
    });
    xhr.send();

    function handler() {
        if (this.readyState === this.DONE) {
            if (this.status === 200) {
                var content = iframe[0].contentWindow ||
                    iframe[0].contentDocument.document || 
                    iframe[0].contentDocument;
                content.document.open();
                content.document.write(this.response.documentElement.innerHTML);
                content.document.close();
            } else {
                iframe.attr('srcdoc', '<html><head></head><body>Error loading page.</body></html>');
            }
        }
    }
}

对courajs喊叫:https://github.com/courajs/pdf-poc/blob/master/script.js

答案 3 :(得分:2)

由于createObjectURL的贬值,@ FellowMD答案在现代浏览器上不起作用,因此我使用了相同的方法,但使用了iframe srcDoc属性。

  1. 使用XMLHttpRequest或其他任何方法检索要在iframe中显示的内容
  2. 设置iframe的srcdoc参数

请在下面找到一个React示例(我知道这太过分了):

import React, {useEffect, useState} from 'react';

function App() {
  const [content, setContent] = useState('');


  useEffect(() => {
    // Fetch the content using the method of your choice
    const fetchedContent = '<h1>Some HTML</h1>';
    setContent(fetchedContent);
  }, []);


  return (
    <div className="App">
      <iframe sandbox id="inlineFrameExample"
              title="Inline Frame Example"
              width="300"
              height="200"
              srcDoc={content}>
      </iframe>


    </div>
  );
}

export default App;

大多数浏览器现在都支持Srcdoc。 Edge似乎实施起来有些迟了:https://caniuse.com/#feat=iframe-srcdoc