EN
JavaScript - window.close() doesn't work
2 answers
0 points
Hello, can you tell me why my code doesn't close the window on the click event when I copy/paste the path to the index.html
file in the web browser but when I open it by double clicking the index.html
file it works fine?
My code:
xxxxxxxxxx
1
2
<html>
3
<body>
4
<button onclick="window.close()">close this window</button>
5
</body>
6
</html>
2 answers
6 points
In modern web browsers, only in some cases you can close the window, e.g. when you open new window by script, you can close it too.
Hint: run it on some server to see the effect.
I have used static resources server extension for VS code.
Preview:
opener-window.html
file:
xxxxxxxxxx
1
2
<html>
3
<body>
4
<button onclick="window.open('closeable-window.html')">open new window</button>
5
</body>
6
</html>
closeable-window.html
file:
xxxxxxxxxx
1
2
<html>
3
<body>
4
<button onclick="window.close()">close this window</button>
5
</body>
6
</html>
0 commentsShow commentsAdd comment
3 points
For security reasons only the script that opens the window can close it.
If you check the console, you should have the following warning:
xxxxxxxxxx
1
Scripts may close only the windows that were opened by them.
0 commentsAdd comment