javascript 如何在javascript中调用另一个窗口的函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25517800/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 04:37:36  来源:igfitidea点击:

How to call a function of another window in javascript?

javascriptjqueryhtml

提问by omega

I open a new tab using window.open. The new tab has a javascript myfunctionfunction in it defined in a script tag. From the window that opens the new window, I want to run that function.

我使用 window.open 打开一个新选项卡。新选项卡myfunction在脚本标记中定义了一个javascript函数。从打开新窗口的窗口中,我想运行该功能。

How can I do that?

我怎样才能做到这一点?

Thanks

谢谢

Something like

就像是

var a = window.open("mypage.html", "_blank");
a.myfunction("hi");

EDIT

编辑

This isn't working. Its not doing the alert.

这不起作用。它没有做警报。

opener

开瓶器

        var w = window.open("../scripts/map.php", "_blank");
        w.postMessage("The user is 'bob' and the password is 'secret'", "*");

new tab

新标签

        function receiveMessage(event) {
            alert(event.data);
        }
        window.addEventListener("message", receiveMessage, false);

回答by HDT

var a = window.open("mypage.html", "_blank");
a.focus();

a.addEventListener('load', function(){
  a.myfunction("hi");
}, true);

回答by The One and Only ChemistryBlob

Assuming a php file provides the content for the new window:

假设一个 php 文件为新窗口提供了内容:

window.open('http://www.example.com/myFile.php?parameter=' + parameter, 'myWindow', 'width=500,height=500,scrollbars=yes').focus();

Then in the php section of myFile.php:

然后在 myFile.php 的 php 部分:

$myParam = (isset($_GET['parameter'])) ? $_GET['parameter'] : null;

Then using a body onload call a function:

然后使用主体 onload 调用一个函数:

<head>
<script>
    var myParam = '<?= $myParam ?>';
</script>
</head>
<body onload="myFunction()">

The function tests for the existence of $myParam:

该函数测试 $myParam 是否存在:

function myFunction() {
    if (myParam) {
        //do Something
    }
}