JavaScript 能否在弹出窗口关闭时检测到弹出窗口并重新打开它

Can JavaScript detect a popup window when it closes and reopen it?

本文关键字:窗口 新打开 检测 JavaScript      更新时间:2023-09-26

我有一个HTML页面,弹出打开一个应用程序的全屏窗口。我想做的是检测弹出窗口何时关闭并重新打开它。

var drawingwindow;
function popup(url) 
{
 params  = 'width='+screen.width;
 params += ', height='+screen.height;
 params += ', top=0, left=0'
 params += ', fullscreen=yes';
 params += ', resizeable=no';
 newwin=window.open(url,'drawingwindow', params);
 if (window.focus) {newwin.focus()}
 return false;
}

然后我触发了 HTML 按钮的弹出窗口

<input type="submit" name="submit" value="Submit" onclick="popup('hello.php')"/>

我想做的是以某种方式检查绘图窗口的第一页 - 如果它关闭 - 立即重新打开它。它是主画布"绘图窗口"上的绘图应用程序的一部分,它有一种方法可以永久关闭绘图窗口。

最近浏览器安全性的改进意味着你不能很好地做你想做的事情。

您可以检测到弹出窗口已关闭:

var popupWindow;
var pop = function () {
    popupWindow = window.open("example.html"); // has to be on same domain as original file
    // setting a popupWindow.onclose event doesn't work (it 
    // fires immediately).  You can fake it by observing some 
    // known property of the popup window, such as its location:
    var fakeOncloseEvent = window.setInterval(function () {
        if (!popupWindow.location) {
            // The popup was closed.
            window.clearInterval(fakeOncloseEvent); // tidy up 
            pop(); // <-- But this won't work!
        }
    }, 250);
}

在大多数浏览器中,重新打开弹出窗口将被阻止,因为您只能在用户直接操作(即点击)的情况下打开新窗口。 (您可以使用上述内容来指导用户自行重新打开弹出窗口,也许通过突出显示"打开弹出窗口"链接,但您无法为他们打开它。

或者,您可以从另一端解决问题,并将代码放在弹出窗口中以防止其关闭。 但是大多数浏览器都严格限制了您在onbeforeunload事件中被允许执行的操作 - 您几乎仅限于抛出确认对话框:

window.onbeforeunload = function() {
  // Just return the string, don't return a confirm() here.
  // Various browsers will include their own additional text 
  // in the confirm dialog, and some may ignore your added text altogether.
  return "Are you sure you want to close this beautiful popup?";
}