如何确定具有给定名称的窗口是否已打开

时间:2012-01-21 10:47:22

标签: javascript window

我想在第一次访问时打开弹出窗口。如果弹出窗口关闭,我想在下次刷新时重新打开弹出窗口。我尝试过使用cookies,但我无法弄清楚如何通知关闭窗口以删除cookie。

是否可以使用window.name了解窗口是否已打开?

if (window.name==MsgWindow) 
{
    openWin();
}

function openWin()
{
    myWindow=window.open('','MsgWindow','width=200,height=100');
    myWindow.document.write("<p>This window's name is: " + myWindow.name + "</p>");
}

3 个答案:

答案 0 :(得分:1)

我认为如果只有窗口的名称,没有直接的方法可以检查窗口是否仍然打开。

但是,对于您的情况,您可以执行以下操作:

// get reference to 'MsgWindow' (will open a new blank window if popup has been closed)
var popupWindow = window.open('', 'MsgWindow', 'width=200,height=100');

// keep popup window in background
window.focus();

// if popup window is blank (= has been closed before), load content
if (popupWindow.location.href == "about:blank") {
    popupWindow.location.href == /* your popup url here */;
}

答案 1 :(得分:0)

如果您希望在窗口关闭之前触发事件,可以尝试window.onbeforeunload

答案 2 :(得分:0)

你可以做类似下面的事情

var myWindow = "";

window.onbeforeunload = function(){
  if(myWindow == "" || myWindow.closed){
            openWin();
  }
};

function openWin(){
    myWindow=window.open('','MsgWindow','width=200,height=100');
    myWindow.document.write("<p>This window's name is: " + myWindow.name + "</p>");
}