function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
MattMet86MattMet86 

Page Leave Alert using the Apex Confirm prompt

Can someone help me code a page leave alert for VF?

I found this code for commandbuttons:
onclick="if(!confirm('Did you do everything?')){return};"

which generates a prompt on the page which is exactly what I want except I need this to occur on page leave instead of on a button click.

My goal is to prevent a user from leaving the page without saving.

I have found the code below online but I am not sure how to swap out the function(e) for the action above.

I want to use the Salesforce alert as the browser will always display my text instead of the hit or miss results I get from this code in different browsers.
<script>
    var LeaveAllowed = false;
    var evt = window.attachEvent || window.addEventListener;
    var checkEvt = window.attachEvent ? 'onbeforeunload' : 'beforeunload';
    evt(checkEvt, function(e) {
        if (!LeaveAllowed)
        {
            var msg = 'There may be unsaved changes.';
            (e || window.event).returnValue = msg;
            return msg;
        }
    });

    function allowLeave()
    {
        LeaveAllowed = true;
    }

</script>

Thanks,
Paul Allsopp 3Paul Allsopp 3
Try this:
<script>
    window.onunload = function(e) {
        return (confirm('Did you do everything?'))
    });
</script>

I'm not able to test it right now, but that should work or something very similar
Paul Allsopp 3Paul Allsopp 3
[EDIT]
<script>
    window.onunload = function(e) {
        return (confirm('Did you do everything?'))
    }
</script>

 
MattMet86MattMet86
I tried the code exactly as you typed it and it didn't work. I also tried to replace the center code with your command and that still didn't work. 
Ideas?
<script>
    var LeaveAllowed = false;
    var evt = window.attachEvent || window.addEventListener;
    var checkEvt = window.attachEvent ? 'onbeforeunload' : 'beforeunload';
    evt(checkEvt, function(e) {
        if (!LeaveAllowed)
        {
            return (confirm('Did you do everything?'));
        }
    });

    function allowLeave()
    {
        LeaveAllowed = true;
    }

</script>