首页 > web前端 > javascript window.open 父子窗口通讯

javascript window.open 父子窗口通讯

2013年7月27日 发表评论 阅读评论

js中可以使用window.open来弹出一个新窗口。例如一下代码可以弹出一个居中的窗口:

var __popupReference = null;

function openExplorerPopUp(url, width, height) {
    if (isNaN(width)) {
        width = 1000;
    }
    
    if (isNaN(height)) {
        height = screen.height * 0.8;
    }

    x = (screen.width - width) / 2;
    y = (screen.height - height) / 2;

    if ((null != __popupReference) && (undefined != __popupReference)) {
        __popupReference.close();
    }
    
    if (url.length > 0) {
        var style = "toolbar=no,location=no,directories=no,menubar=no,scrollbars=no,resizable=no,status=no,width=" + width + ",height=" + height + ",left=" + x + ",top=" + y;
        __popupReference = window.open(url, '', style);
        
        try {
            if (window.focus()) {
                __popupReference.focus();
            }
        } catch(e) {}
    }
}

如何让父窗口和弹出的新窗口进行通讯呢?下面分别阐述。

先看父窗口与子窗口如何通讯。注意上面代码中有一行“__popupReference.close();”,其用途就是用于关闭弹出的窗口,我们知道在js中可以使用window.close()来关闭当前窗口,通过行为可以得出__popupReference对象其实就是window对象结论,只不过是子窗口的。所以window.open返回值也就是子窗口的句柄了,有了这个句柄,在父窗口就可以操作子窗口的DOM、js定义的function等。例如:__popupReference.document.getElementById(‘subDomId’).style.display = ‘none’; __popupReference.subWinDefineFunction()。

在子窗口中只要能拿到父窗口的句柄,那么就能进行通讯。在内置的window对象中有一个opener属性,就是其父窗口的句柄。有了这个,通讯就很容易了。例如:
window.opener.getElementById(‘parentDomId’).style.display = ‘none’; window.opener.parentDefineFunction();



欢迎转载,转载请注明文章出处,谢谢!
垃圾有点差凑合看还不错很精彩 (1 人打了份: 平均分:4.00)
Loading...Loading...
分类: web前端 标签:
  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.

无觅相关文章插件,快速提升流量