javascript - 在子窗口中从父窗口运行JS函数?

标签 javascript jquery

想要在子窗口中从父窗口运行javascript函数

示例

我必须访问不同的网站,例如 site1.comsite2.com

我想从 site1.com 打开 URL site2.com 的新窗口

new_window = window.open("site2.com/index.php", "window2");

然后我想在这个new_window上运行一个js函数test()

// Where site2.com/index.php 
<html>
    ......
</html>
<script>
   function test(){
    // some code here
   }
</script>

摘要

想要打开新窗口(子窗口)并从父窗口运行一些 JS 函数。

最佳答案

您可以使用cross document messaging规避同源政策如下。

父窗口 (site1.com):

var site2 = window.open("http://site2.com");
site2.postMessage("test", "http://site2.com");

子窗口(site2.com):

function test() {
    // some code here
}

window.addEventListener("message", function (event) {
    if (event.origin === "http://site1.com") {
        var funct = window[event.data];
        if (typeof funct === "function")
            funct();
    }
}, false);

这是一个简单的例子。您可以使其变得更加复杂,以允许回调、返回值等,但这需要一篇博客文章进行充分解释。

您可以在 Mozilla Developer Network 上阅读有关 window.postMessage 的更多信息。 .

但请注意,以下示例显然无法在 Internet Explorer 中运行。

关于javascript - 在子窗口中从父窗口运行JS函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11010743/

相关文章:

javascript - 寻路: How to create path data for the pathfiding algorithm?

javascript - 如何从不同的组件调用其他组件功能?

javascript - 将通知消息滚动到固定菜单底部

javascript - 检测浏览器是否阻止弹出窗口

jquery - 使用ajax间隔刷新时如何停止文本或元素的闪烁?

javascript - Ngfor 对象列表并从主数组中的对象之一内的数组再次循环

jquery - 如何仅在 iframe 中查看时隐藏元素

需要两个输入的 javascript 函数 : an object and a key and returns the corresponding value for that key within the object

jQuery点击功能增加不透明度

php - 调试 JavaScript 代码