3

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

I have User agreements and they are opened in new window and this works (when i try to close the window)

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

But what i would like to accomplish is that if user go directly to /agreeement and clicks close that it redirects him to the homepage. Because now if i do that 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 make a check where if the window was not open from a script redirect to index. But i dont how would i make that check

MePo
  • 964
  • 2
  • 20
  • 45

2 Answers2

5

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
  • 381
  • 4
  • 16
Sufyan Jabr
  • 731
  • 4
  • 20
  • 1
    If it's a duplicate don't post an answer with the link, mark it as duplicated. – Marcos Pérez Gude Jul 05 '16 at 07:52
  • I will try this and give you an answer. Thanks – MePo Jul 05 '16 at 07:52
  • @MarcosPérezGude the other question is different – Sufyan Jabr Jul 05 '16 at 07:53
  • But provides an answer to this question. Stackoverflow is not a custom service, is a site where all questions will be useful to other users. If we only answer to particular cases this community will lost its sense – Marcos Pérez Gude Jul 05 '16 at 07:54
  • 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,299
  • 2
  • 23
  • 29