我想在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

对于我的用例而言,重要的是,代码必须以正确的全局变量运行; windowdocument等都应限制为iframe本身。

我还有其他方法可以做到这一点吗?上面的方法可以工作,但是脚本需要在所有具有不同CSP规则的域上运行,这意味着增加了对现时/哈希等的支持。

是否可以做类似的事情:
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);
});

而且它仍然按预期工作。

09-25 18:06
查看更多