Languages

JavaScript - window.close() doesn't work

0 points
Asked by:
Hayley-Mooney
677

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
Answered by:
Hayley-Mooney
677

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
Answered by:
Hayley-Mooney
677

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
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join