Javascript,调用父窗口的子窗口函数不起作用

13

我正在开发一个使用window.open(..)打开弹出窗口的Web应用程序。我需要使用“window.open”返回的句柄调用已在子窗口中声明的函数,但是我总是收到错误消息“addWindow.getMaskElements不是函数”,好像无法访问子窗口上声明的函数。这在IE和FF中都是如此。我的代码看起来像这样:

function AddEmail(target,category)
{
    if(addWindow == null)
    {
        currentCategory = category;
        var left = getDialogPos(400,220)[0];
        var top =  getDialogPos(400,220)[1];
        addWindow = window.open("adicionar_email.htm",null,"height=220px, width=400px, status=no, resizable=no");
        addWindow.moveTo(left,top);
        addWindow.getMaskElements ();
    }
}

我已经通过谷歌和不同的可靠来源阅读了一些内容,显然这应该是能够工作的,但它并没有。还有一件事,子窗口中的函数声明在一个单独的.js文件中,该文件包含在adicionar_email.htm文件中。这会有什么影响吗?不应该有影响...因此,如果有人遇到类似的问题,或者有任何关于我做错了什么的想法,请回复这条消息。提前致谢。

肯尼亚


moveTo 是否有效?对于另一个函数,可能存在竞争条件;如果设置一个计时器等待 .getMaskElements 存在,它是否会完成? - Anonymous
4个回答

12

创建窗口不会阻塞操作。在窗口打开、加载HTML、JavaScript并解析它的同时,脚本将继续执行。

如果您在原始页面上像这样添加一个链接:

<a href="#" onclick="addWindow.getMaskElements();">Test</a>

我试过了,它能正常工作。(只是为了确保一下。)

**编辑**

有人通过在目标文档中调用 onload 发布了一个解决方法,这里提供另一种方法:

function AddEmail()
{

        if(addWindow == null) {
        addWindow = window.open("test2.html",null,"height=220px, width=400px, status=no, resizable=no");
        }

        if(!addWindow.myRemoteFunction) {
            setTimeout(AddEmail,1000);
        } else { addWindow.myRemoteFunction(); }
}
这会不断尝试每1秒钟调用addWindow.myRemoteFunction函数,直到成功调用为止。

5
问题在于window.open方法会很快返回,但是请求的文档以及该文档可能引用的其他任何项目都尚未加载到窗口中。因此,尝试这么早调用该方法将失败。您应该将一个函数附加到打开窗口的load事件,并尝试从该函数进行调用。

3
下面代码的问题是:
当父窗口中的JavaScript被执行时,子窗口没有加载。因此,来自父窗口的调用函数处于无限循环状态,并且导致窗口崩溃。

The window creation is not a blocking operation; the script continues to execute while that window is opening and loading the HTML & javascript and parsing it.

If you were to add a link on your original page like this:

<a href="#" onclick="addWindow.getMaskElements();">Test</a>

You'd see it works. (I tried it just to be sure.)

**EDIT **

Someone else posted a workaround by calling an onload in the target document, here's another approach:

function AddEmail()
{

        if(addWindow == null) {
        addWindow = window.open("test2.html",null,"height=220px, width=400px, status=no, resizable=no");
        }

        if(!addWindow.myRemoteFunction) {
            setTimeout(AddEmail,1000);
        } else { addWindow.myRemoteFunction(); }
}

This keeps trying to call addWindow.myRemoteFunction every 1 second til it manages to sucessfully call it.


1

您正在打开窗口后立即调用该函数;弹出窗口上的页面可能尚未加载,因此在此时该函数可能尚未定义。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接