【问题标题】:Is there a way to determine if the browser window is a popup, or just a new window using target="_blank"?有没有办法确定浏览器窗口是弹出窗口,还是使用 target="_blank" 的新窗口?
【发布时间】:2016-07-12 23:47:48
【问题描述】:

我正在维护一个大型应用程序。在某些区域,我必须检查当前窗口是弹出窗口(使用 window.open() 打开)还是新窗口(使用 target="_blank" 打开新选项卡或窗口)。

这是我的问题的一个例子:

    function CancelOutOfPage(cancelPath) {
        if (cancelPath != null && cancelPath != "" && window.opener == null) {
            location.href = cancelPath;
        } else if (referrerUrl != "" && window.opener == null) {
            // Just go back
            location.href = referrerUrl;
        } else {
            // It is a popup, close it.
            // MY PROBLEM IS HERE. IF THE WINDOW IS NOT A POPUP, BUT A AN OPENED PAGE
            // THE WHOLE WINDOW WILL CLOSE
            window.close();
        }
    }

【问题讨论】:

  • @ZuraSekhniashvili 我做到了,但如果我理解正确,我们可以确定窗口是否在“弹出窗口内或 target=_blank 窗口内”,如果 window.opener 是不为空。但是如何检查我是在弹出窗口内,还是在 target=_blank 内?
  • @VinShahrdar 是否从您的应用程序中打开了新的window
  • @guest271314 是的,来自许多不同的来源。

标签: javascript jquery google-chrome popup


【解决方案1】:

您可以在打开弹出窗口时设置一个全局变量,然后如果变量是真实值,您就会知道这是一个弹出窗口 - 如果它是 undefined,它将是 false

在调用页面中:

var popupWindow = window.open(page);
popupWindow.isPopup = true;

在新窗口中:

if (window.isPopup) { 
    window.close();
}

更新:

您也可以在使用弹出窗口打开时设置window 的名称。 window.open 函数采用第二个参数作为名称,后跟可选的窗口功能。

在调用页面中:

window.open("test.html", "Test Popup");

在新窗口中:

if (window.name.length) { 
    window.close();
}

【讨论】:

  • 问题是整个系统中可能有数百个窗口打开。我想知道是否有一种方法可以用最少的努力来处理这个问题。检查 window.name 会起作用吗?我可能错了,但是 window.name 仅在我们打开新弹出窗口时设置。
  • @VinShahrdar 是的,这也应该有效。查看更新的答案。
【解决方案2】:

您可以在打开窗口时在窗口上显示标志。

//in window from which you open new window
var w = window.open('');
w.someFlag = true;

//in opened window
console.log(window.someFlag);
if (window.someFlag){
    //do what you want
}

【讨论】:

    【解决方案3】:

    您可以通过向window.open() 提供第二个参数来设置新windowname,例如;

     var w = window.open("url", "__blank__")
    

    在打开window

     if (this.name === "__blank__") {/*do stuff*/} else {/*do other stuff*/}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多