简体   繁体   中英

Confirmation before leaving/closing of tab?

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.

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 = '';
});

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM