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.
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