我想在 iframe 窗口的上下文中运行一些 javascript。现在我能想到的唯一方法是注入(inject)一个脚本标签:
myIframe = document.createElement('iframe');
myIframe.setAttribute('name', 'xyz123');
document.body.appendChild(myIframe);
myIframe.contentWindow.document.write(`
<script>
console.log('The current window name is:', window.name);
</script>
`);
注意:这是同域 iframe,没有 src,所以我可以完全访问 contentWindow
。
对于我的用例来说,代码使用正确的全局变量运行很重要; window
、document
等都应该限定在 iframe 本身。
有没有其他方法可以做到这一点?以上有效,但脚本需要在具有不同 CSP 规则的不同域上运行,这意味着添加对 nonces/hashes 等的支持。
是否可以这样做:
myIframe.contentWindow.run(function() {
console.log('The current window name is:' window.name);
});
我已经尝试了 myIframe.contentWindow.setTimeout
但它似乎仍然在父窗口的上下文中运行代码。
最佳答案
您实际上可以创建该 run
函数,然后将回调函数应用于 this
,这当然是 iframe 上下文。然后您可以使用 this
访问 iframe 元素:
myIframe.contentWindow.run = function(fn) {
fn.apply(this);
};
myIframe.contentWindow.run(function() {
console.log('(run) The current window name is:', this.window.name);
});
控制台输出
(run) The current window name is: xyz123
您可以在此处查看我的示例:http://zikro.gr/dbg/html/con-frame/
编辑
如果你只想使用 window
而不是 this.window
,那么你可以为内联函数创建一个参数,名称为 window
,然后像这样将 this.window
传递给该函数:
myIframe.contentWindow.run = function(fn) {
fn.call(this, this.window);
};
myIframe.contentWindow.run(function(window) {
console.log('(run) The current window name is:', window.name);
});
它仍然按预期工作。
关于javascript - 在框架窗口的上下文中运行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45993415/