开发者

How to collect return value of onbeforeunload

开发者 https://www.devze.com 2023-03-17 13:31 出处:网络
I am displaying a warning message if user try to close window without saving the form. window.onbeforeunload = askConfirm;

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;
        }   
    }


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号