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:
<!doctype html>
<html>
<body>
<button onclick="window.close()">close this window</button>
</body>
</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:
<!doctype html>
<html>
<body>
<button onclick="window.open('closeable-window.html')">open new window</button>
</body>
</html>
closeable-window.html
file:
<!doctype html>
<html>
<body>
<button onclick="window.close()">close this window</button>
</body>
</html>
0 comments
Add 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:
Scripts may close only the windows that were opened by them.
0 comments
Add comment