Question

I have the following code

<script type="text/javascript">
function PopIt() { return 'Are you sure you want to leave?'; }
function UnPopIt() { /* nothing to return */ }

$(document).ready(function() {
window.onbeforeunload = PopIt;
$('a').click(function(){ window.onbeforeunload = UnPopIt; });
});
</script>

This script works. But how do I alter it so it works like this;

1) User presses exit tab/page

2) page changes to one of my choice

3) exit popup displays with yes or no to leave

4) yes = close page, no = stay on current page

I'd like the page to change before the popup displays

Thanks.

Note: I do have control over the pages, I wish to redirect to another .php in the same folder.

Was it helpful?

Solution

Try using both onbeforeunload and onunload together like this...

    function PopIt() { 
        return 'Are you sure you want to leave?';
    }
    function UnloadIt() {
        window.opener.nowDoThisOpener("pass this variable along too");
    }

    $(document).ready(function() {
        //set the function defining what should be done BEFORE unloading
        window.onbeforeunload = PopIt;
        //set the function defining what should be done ON unloading
        window.onunload = UnloadIt;
        //set all links to disable both of these on click
        $('a').click(function(){ 
            window.onbeforeunload = null;
            window.onunload=null;
        });
    });

Note that nowDoThisOpener is a function that you can define (And obviously call whatever you want) on the parent page. And, like I've suggested, you can pass along information too.

Also, in your example you were setting an empty function UnPopIt to cancel the onbeforeunload. That's unnecessary, you can just set the onbeforeunload to null, as well as the onunload, as I've done in my example.

Previous Answer:

Could you put some kind of flag in the hash when you redirect? So instead of sending off to http://www.pageofmy.com/choice.php you sent to http://www.pageofmy.com/choice.php#1

Then on choice.php you could have...

<script>
if (location.hash=="#1") {
   //show alert
}

</script>

This assumes that you have control over pageofmy.com/choice.php. If you're redirecting to some other site you don't have control over, I don't see how you can do this besides attempting to have a popup window come up (which will most likely be blocked by modern browsers)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top