【发布时间】:2018-02-10 02:47:04
【问题描述】:
我想在 iframe 窗口的上下文中运行一些 javascript。现在我能想到的唯一方法是注入一个脚本标签:
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/hash 等的支持。
是否可以这样做:
myIframe.contentWindow.run(function() {
console.log('The current window name is:' window.name);
});
我已经尝试过myIframe.contentWindow.setTimeout,但这似乎仍然在父窗口的上下文中运行代码。
【问题讨论】:
标签: javascript html browser