打开和关闭javascript窗口

打开和关闭javascript窗口,javascript,html,Javascript,Html,我想关闭浏览器窗口,无论它是否处于打开状态。我是javascript新手,所以请帮助我使用javascript创建以下逻辑。我的JavaScript代码如下: if (myWindow.open() == true) { myWindow.close(); } else { myWindow=window.open('http://index.html', 'popUpWindow',

我想关闭浏览器窗口,无论它是否处于
打开状态
。我是javascript新手,所以请帮助我使用javascript创建以下逻辑。我的JavaScript代码如下:

if (myWindow.open() == true) {
    myWindow.close();
} else {
    myWindow=window.open('http://index.html',
                         'popUpWindow',
                         'height=700,width=800,left=10,top=10,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no,status=yes'
                         );
}

是的,我同意克里斯托夫的观点

if (!myWindow.closed) {
    myWindow.close();
} 
更进一步


注意:与上述内容存在特定于浏览器的差异。如果您使用
Javascript(通过window.open())
打开窗口,则允许您使用Javascript关闭窗口,前提是您拥有本案例中的引用。Firefox不允许您关闭其他窗口。我相信IE会要求用户确认。其他浏览器可能会有所不同

您已接近正确的结果

检查一下

(myWindow.closed === false) // same as (!myWindow.closed)
而不是

(myWindow.open() == true)
(因为
open()
将打开另一个窗口,您的检查将失败。)


还要注意,您需要编写
index.html
http://sub.yourdomain.tld/index.html
,但不是
http://index.html

使用
closed
属性检查窗口状态,但首先检查窗口对象是否已创建

var myWindow=null;
if (myWindow && !myWindow.closed) { //exist and is not closed
    myWindow.close();
    myWindow=null; //delete the object
} else { //not exist or is closed
    myWindow=window.open('http://index.html',
                         'popUpWindow',
                         'height=700,width=800,left=10,top=10,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no,status=yes'
                        );
}