我有一个页面,我在其中动态创建一个空的 iframe。然后我需要通过检索一些 js 脚本响应数据来填充 iframe 内容。当我调用 js URL 时一切正常:
(function(d) {
var iframe = d.body.appendChild(d.createElement('iframe')),
doc = iframe.contentWindow.document,
options = {
objid: 152,
key: 316541321
},
src = "host/widget.js",
uri = encodeURIComponent(JSON.stringify(options));
iframe.id = "iframewidget";
iframe.width = 200;
iframe.height = 300;
var html = '<body onload="var d=document;' +
'd.getElementsByTagName(\'head\')[0].appendChild(d.createElement(\'script\')).src=\'' + src + '\'">';
doc.open().write(html);
doc.close();
})(document);
但我需要使用一些动态参数运行 widget.js。有没有办法将 uri 变量值传递给脚本?我使用纯 JavaScript,而不是 jQuery
最佳答案
下面是对代码的快速修改,以展示其可能性。
您的 doc 变量是 iFrame 的文档元素。在其上设置一个变量将允许您从 iFrame 中运行的代码访问它。
https://jsfiddle.net/78gf5e8q/
(function(d) {
var iframe = d.body.appendChild(d.createElement('iframe')),
doc = iframe.contentWindow.document,
options = {
objid: 152,
key: 316541321
},
//src = "host/widget.js",
uri = encodeURIComponent(JSON.stringify(options));
doc.someVar = "Hello World!";
iframe.id = "iframewidget";
iframe.width = 200;
iframe.height = 300;
var html = '<body onload="var d=document;' +
'd.getElementsByTagName(\'head\')[0].appendChild(d.createElement(\'script\')).innerHTML=\'alert(document.someVar)\'">';
doc.open().write(html);
doc.close();
})(document);
编辑:您还将一个名为 js 的不存在的变量传递到 doc.open().write(js) 中;我将其更改为 .write(html);
编辑 2:对于跨域,您可能会在该变量上收到“权限被拒绝”的消息。
关于javascript - 来自js响应的动态iframe内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42154398/