javascript - 如何使用带有标头的 POST 加载 iframe
问题描述
我需要将网页加载到 iframe 中。网页服务器由 Open ID Connect 保护,需要一个不记名令牌进行授权。为了呈现页面,还需要通过服务器发送数据。响应的内容也有一些 JavaScript。iframe src 只允许有一个使用 GET 方法的 URL,它不能提供我们想要的。
总而言之,我需要:
- 使用 POST 将网页加载到 iframe
- 在 Authorsation 标头中包含令牌。
- 在 iframe 中加载页面后加载 javascript
解决方案
我采用的方法是使用 AJAX post 来加载页面 html 和 JavaScript 的内容。获得内容后,我们将内容写入 iframe contentwindows。我研究了一些替代方法: - 使用表单发布。这不允许将令牌包含到授权标头中 - 使用 jQuery html 方法。这不会触发 iframe 加载 html。所以返回页面中的 JavaScript 不起作用。
工作示例:https ://jsfiddle.net/duongthaiha/wmLsrfo0/52/
这是一些代码片段:
function loadHTMLToIframe(data) {
alert(data);
var iframe = document.getElementById('targetIframe');
var iframedoc = iframe.document;
if (iframe.contentDocument)
iframedoc = iframe.contentDocument;
else if (iframe.contentWindow)
iframedoc = iframe.contentWindow.document;
if (iframedoc){
// write content to the iframe
iframedoc.open();
iframedoc.writeln(data);
iframedoc.close();
//page loaded at this point
} else {
alert('Fail to get the content windows');
}
}
参考:http ://thinkofdev.com/javascript-how-to-load-dynamic-contents-html-string-json-to-iframe/
推荐阅读
- django-channels - 安装频道后 Daphne 抛出 500 内部服务器错误
- html - 正则表达式在 html 的 href 和 src 链接中有效的相对 url
- ios - 训练与随机初始化的 cnn 模型。推理速度的差异
- android - 如何让我的慢 ViewPager 工作得更快
- javascript - Service Worker:如何缓存第一个(动态)页面
- hadoop - 如何在命令行中使用 hive.cli.print.header=true 启动 hive?
- r - 在两排中间放一个盒子
- excel - 如何使用 VBA 获取组中所有成员的列表?
- javascript - 如果 value =="string" 否则如何替换 ng-repeat 中的值
- jqgrid - jqgrid在按钮点击上加载