javascriptjquerycallbackonunload

Disable Browser onUnload on certain links?


I am working on a Web Hosting panel which has a DNS records manager. I have to use a lot of JavaScript to make it perform almost like a desktop application.

I really wanted to show a Custom Dialog window when a a browser runs beforeunload however after some research I have discovered I am stuck using the browsers default Dialog window.

So this JavaScript code below does just that, my problem is I need to make sure it does NOT get fired off on certain link clicks.

I am hoping to be able to maintain an Array of CSS class names, and if the link clicked is in this array then it will NOT show the onunload event.

I'm sure this is easy for a JavaScript developer. Could someone show me how to do this?

//sample Class array
safeLinks = ['test', 'test2', 'test3', 'test4', 'test5'];

// onunload event
$(window).on('beforeunload', function(){
  return 'Are you sure you want to leave?';
});

Solution

  • You could remove the event handler when they're clicked:

    var safeLinks = ['.test', '.test2', '.test3', '.test4', '.test5'];
    
    function promptBeforeClose() {
        return 'Are you sure you want to leave?';
    }
    
    $(window).on('beforeunload', promptBeforeClose);
    
    $(document).on('click', safeLinks.join(', '), function(e) {
        $(window).off('beforeunload', promptBeforeClose);
    });
    

    Also, if these safe links have a common ancestor, use that instead of document as the delegation parent or people will complain. ;)