Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional onbeforeunload event in a page

window.onbeforeunload = function(evt) {
    var message = 'Are you sure you want to leave the page. All data will be lost!';

    if (typeof evt === 'undefined') {
        evt = window.event;
    }
    if (evt && !($("#a_exit").click)) {
        evt.returnValue = message;
    }
    return message;
};

I want user to leave the page clicking to the link (has id ="a_exit") only. In other circumstances such as refreshing the page, clicking another link, user will be prompted that if he/she wants to leave the page. I have tried to use the code above. It still asks me if I want to go away when I click the exit link.

like image 373
zkanoca Avatar asked Nov 20 '13 11:11

zkanoca


People also ask

How do I trigger a Beforeunload event?

The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point. This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page.

Can I use Onbeforeunload?

This feature is deprecated/obsolete and should not be used.

How do I stop Windows unloading?

Since jQuery 1.4, you can bind the 'beforeunload' event to $(windows) object to stop a page from exit , unload or navigating away. $(window). bind('beforeunload', function(){ return ''; });

What is Onbeforeunload in JS?

The onbeforeunload event occurs when the document is about to be unloaded. This event allows you to display a message in a confirmation dialog box to inform the user whether he/she wants to stay or leave the current page. The default message that appears in the confirmation box, is different in different browsers.


2 Answers

You can return null when you do not want the prompt to show. Tested on Chrome 79.

window.onbeforeunload = () =>  {
    if(shouldPrompt){
       return true
    }else{
       return null
    }
}

BTW modern browser no longer support custom onBeforeUnload promp text.

like image 195
Dragonduck Avatar answered Oct 22 '22 21:10

Dragonduck


My quick example of the conditional prompt before leaving page:

    window.onbeforeunload = confirmExit;
    function confirmExit(event) {
        var messageText = tinymce.get('mMessageBody').getContent();
        messageText = messageText.trim();

        // ... whatever you want

        if (messageText != "")
            return true;
        else
            return void (0);
   };

It works under Chrome, FF.

like image 35
Sergey Avatar answered Oct 22 '22 22:10

Sergey