想要在子窗口中从父窗口运行javascript函数
示例
我必须访问不同的网站,例如 site1.com
和 site2.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/