1
votes

I'm maintaining a large application. In some areas, I have to check if the current window is a popup (opened using window.open()) or a new window (a new tab or window opened using target="_blank").

Here is an example of my problem:

    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();
        }
    }
3
@ZuraSekhniashvili I did, but if I'm understanding this correctly, we can determine if the window is "'inside a pop-up window or target=_blank window'" if the window.opener is not null. But How do I check if I'm just inside a popup window, or just inside a target=_blank?Vin Shahrdar
@VinShahrdar Is the new window opened from you application?guest271314
@guest271314 Yes, from many different sources.Vin Shahrdar

3 Answers

1
votes

You could just set a global variable when you open the popup, and then you know it's a popup if variable is a truthy value - if it's undefined it will be false:

In the calling page:

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

In the new window:

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

Update:

You could alternatively set the name of the window when you open with a popup. The window.open function takes a second parameter for the name, followed by optional window features.

In the calling page:

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

In the new window:

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

You can give flag on window when you open it.

//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
}
0
votes

You can set the name of the new window by providing second parameter to window.open(), e.g.;

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

at opened window,

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