3

I'm trying to show a confirmation pop before user close the tab or went to another tab like facebook, gmail, GoDaddy & others do.

My code working for Firefox but not for other browser like chrome, safari etc.

<script type="text/javascript">
      var hook = true;
      window.onbeforeunload = function() {
        if (hook) {
          return "Did you save"
        }
      }
      function unhook() {
        hook=false;
      }
    </script>

Call unhook() onClick for button and links

<a href="http://example.com" onClick="unhook()">No Block URL</a>

Please help me to get this fixed.

Jyoti Sandhiya
  • 173
  • 3
  • 12
  • Do you know the modal? Do you want modal like this?https://getbootstrap.com/docs/4.1/components/modal/ – Arman Bagheri Jan 17 '19 at 05:37
  • Possible duplicate of [Confirmation before closing of tab/browser](https://stackoverflow.com/questions/10311341/confirmation-before-closing-of-tab-browser) – adiga Jan 17 '19 at 05:53
  • any error in console? – Prashanth Benny Jan 17 '19 at 06:40
  • It's already asked please check below link https://stackoverflow.com/questions/19263277/open-a-custom-popup-on-browser-window-tab-close – Manish Jan 17 '19 at 07:08
  • It's already asked please check https://stackoverflow.com/questions/19263277/open-a-custom-popup-on-browser-window-tab-close – Manish Jan 17 '19 at 07:10

2 Answers2

4

If you take a look at the api of window.beforeunload(), you can see that, though widely the basic unload event is supported, a custom message can only be set in internet explorer and certain versions of some browsers. So just use the normal standard message.

This feature (custom messages) was often exploited by malicous sites to interact with user in a harmful or malipulative way. This is why many browsers don't support this anymore, until some patch removes the threat for users.

Standard message solution:

window.addEventListener('beforeunload', function (e) {
  // Cancel the event
  e.preventDefault();
  // Chrome requires returnValue to be set
  e.returnValue = '';
});
Stephan T.
  • 5,843
  • 3
  • 20
  • 42
0

Look at Ouibounce it helps detect when a user is about to leave the page(It looks at the position of the cursor). You could probably build off this library.

Mike
  • 587
  • 3
  • 6