0

I have a link in my webpage to close window in javascript :

<a href="#" onclick="window.close()">Close the window</a>

But when I click it, I have this error in console :

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

I have done a search on google, and now, I know why. This is the normal behavior (for security reasons I think).

But when I send the link of my page via Outlook, and then, I click to close the page : It works ! Why ???

k4st0r42
  • 1,174
  • 1
  • 15
  • 29
  • Possible duplicate of [window.close and self.close do not close the window in Chrome](http://stackoverflow.com/questions/19761241/window-close-and-self-close-do-not-close-the-window-in-chrome) – Vladu Ionut Mar 03 '17 at 14:42
  • Do you use the very same browser? For opening your page normally and via Outlook? Another question: do you open the page through a webserver (even localhost) or just locally as a html file? (sometimes it is not the same) – Geza Boehm Mar 03 '17 at 15:31
  • Yes the same : Chrome. And on a webserver – k4st0r42 Mar 03 '17 at 15:35

1 Answers1

0

It may be clear as the error explained. You should use 1 variable to open and then close window, try:

<button onclick="openWin()">Open "myWindow"</button>
<button onclick="closeWin()">Close "myWindow"</button>

<script>
var myWindow;

function openWin() {
    myWindow = window.open("", "myWindow", "width=200,height=100");
    myWindow.document.write("<p>This is 'myWindow'</p>");
}

function closeWin() {
    myWindow.close();
}
</script>
Quyen Anh Nguyen
  • 1,204
  • 13
  • 21