JavaScript: On Close Tab Show Warning Message

Close tab warning message.

Here I am giving an example of JavaScript code which you can use to show a warning message on the close tab.

Before using the below code, I have tried many examples of JavaScript code which I found on Google, but those didn't work.

But this piece of code works perfectly, and now, even I forgot from where I picked 🤔.

On Close Tab Show Warning Message Using JavaScript

Use the following JavaScript code between the head tags:

<script type="text/javascript">
   window.onbeforeunload = function (e) {
      e = e || window.event;

      if (e) {
         e.returnValue = '?';
      }

      // For Safari
      return '?';

   };
</script>

Instead of a '?' mark for the return message value, you can use any warning message text, but it always gives the default Chrome or Safari warning message.

If you want to use this feature in Oracle Apex, check the following post, JavaScript: on close tab show warning message.

Vinish Kapoor

An Oracle Apex Consultant, Oracle ACE, and founder of foxinfotech.in and orclqa.com a question and answer forum for developers.

This Post Has 2 Comments

  1. João Coimbra

    How about hiding ir disabling the X upper right hand side button on a modal page? I used the css display on the class but it leaves a glimpsy of the button before it is definitively hidden?

    1. Vinish Kapoor

      Try the following CSS to hide close button of the dialog page, but apply this CSS on the parent page not on the dialog page:

      body .ui-dialog .ui-dialog-titlebar-close {display: none;}
      

      And on the dialog page, you can try adding the following command for the Dialog > Attributes property:

      closeOnEscape:false
      

Comments are closed.