Ajinkya
Ajinkya

Reputation: 22720

How to collect return value of onbeforeunload

I am displaying a warning message if user try to close window without saving the form.

window.onbeforeunload = askConfirm;

    function askConfirm()
    {
        // needToConfirm is set to true if any changes are there in the form
        if (needToConfirm)
        {
            return "Your unsaved data will be lost.";
        }       
    } 

    function call_this_if_user_clicks_on_cancel()
    {
       // Bla bla bla
       // After this user should remain on the same page.
    }  

Now I want to call another function when user clicks on Okay. And rest of the functionality should remain same. So how can I collect onbeforeunload return value and call another function ?

SOLUTION:

    needToConfirm = false; 
    window.onbeforeunload = askConfirm;
    window.onunload = unloadPage;
    isDelete = true;

    function unloadPage()
    {
        if(isDelete)
        {
           call_this_if_user_clicks_on_cancel() 
        }   
    }

    function askConfirm()
    {
        alert("onbeforeunload");
        if (needToConfirm)
        {
            // Message to be displayed in Warning.
            return "Your data will be lost.";
        } 
        else
        {
            isDelete = false;
        }   
    }

Upvotes: 12

Views: 18127

Answers (1)

Alex KeySmith
Alex KeySmith

Reputation: 17101

I'm not certain; But I would of thought you cannot call another function, as a preventative measure by the browser so it doesn't get trapped from leaving the page.

I think only the browser knows if it's returns true / false to determine if the page is unloaded (or not).

Previously unbeforeunload was non-standard (from IE4, but supported by other browsers) Here are the Mozilla docs https://developer.mozilla.org/en/DOM/window.onbeforeunload And Microsoft docs: http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx

However it looks as thought BeforeUnloadEvent is in the HTML5 proposal. This document gives in detail the steps that happen when a document is unloaded (interesting read):

http://www.w3.org/TR/html5/history.html#beforeunloadevent


As a workaround: You may be able to gather the information you need from the "unload event", if the unload event is NOT called after the onbeforeunload, you could assume that the user chose to stay on your page.

https://developer.mozilla.org/en/DOM/window.onunload

Upvotes: 9

Related Questions