5

Is it possible to check if script opened a window with JavaScript?

I have User agreements and they are opened in a new window and when I try to close the window, this works:

<a href="JavaScript:window.close()" class="btn btn-default">Return</a>

But what I would like to accomplish is that if the user go directly to /agreeement and clicks close, that it redirects him to the homepage.

Using my current code in this case, I get a message:

Scripts may close only the windows that were opened by it.

And I understand why. That is why I would like to check whether the window was not opened from a script, and then redirect to index in that case.

zcoop98
  • 2,590
  • 1
  • 18
  • 31
MePo
  • 1,044
  • 2
  • 23
  • 48

2 Answers2

8

window.opener will be null when the page is not opened by another window, and therefore can not be closed.

This code should should do the trick:

function goAway() {
    if(window.opener === null) {
        window.location.href = '<YOUR_DEFAULT_URL>';
    }
    else {
        window.close();
    }
}

You can find more details here

Matthew Beck
  • 451
  • 5
  • 19
Sufyan Jabr
  • 791
  • 4
  • 20
  • 1
    No it doesn't talk about != null ... it just explains what is window.opener... if you are a new developer reading that will not tell how to check if the page is opened by a script or a new window.... – Sufyan Jabr Jul 05 '16 at 07:55
  • @Marcos Pérez Gude Well i could delete this question then if thats a problem as i didnt knew how to approach this problem so i asked here – MePo Jul 05 '16 at 08:05
  • That's not a problem, we can mark as duplicated and the question will survive to the time, with the correct canonical reference. – Marcos Pérez Gude Jul 05 '16 at 08:11
2

It's been a while since I've needed to do this, but you can get the window that opened the current window with window.opener

conradj
  • 2,481
  • 2
  • 24
  • 30