How to close a page with javascript when clicking on the main closure


I am currently creating a page in html, but I would like you to click on the main button to close a window, I mean ...

and that I get a popup window with a message of caution ... I found that they do with javascript but with a button or link, but there will be to be treated directly with the main button to close.

 <!DOCTYPE html>
<script type="text/javascript">
    window.addEventListener("beforeunload", function (e) {
    var confirmationMessage="\o/";

    e.returnValue= confirmationMessage;
    return confirmationMessage;
<body >

asked by Kevincs7 10.09.2018 в 22:21

1 answer


You can use the beforeunload event from javascript, for example:

window.addEventListener("beforeunload", function (e) {
  var confirmationMessage = "\o/";

  e.returnValue = confirmationMessage;     // Gecko, Trident, Chrome 34+
  return confirmationMessage;              // Gecko, WebKit, Chrome <34


  • It is important that you know that you can not put a confirm/alert   inside the event beforeunload .

  • The texts are different for each browser.

  • Not all browsers support changing the text.
answered by 10.09.2018 в 22:29