Last Updated: February 25, 2016
·
6.294K
· chinchang

Execute code after onbeforeunload modal

Do you want to execute some JS code after the visitor clicks on 'Stay on this page' button in a onbeforeunload modal?

I found a really nice hack to do so. It pushes the code in the next UI cycle using setTimeout which gets executed as soon as the modal closes and execution resumes:

$(function() {
$(window).bind('beforeunload', function() {
    setTimeout(function() {
        setTimeout(function() {
            $(document.body).css('background-color', 'red');
        }, 1000);
    },1);
    return 'are you sure';
});
}); ​

Watch it live here.

Source: http://stackoverflow.com/a/4651049/891962

3 Responses
Add your response

Just forked your script :)
http://jsfiddle.net/yM5n5/1/

over 1 year ago ·

You can shorten and/or abstract that - you can remove some stuff and make that a function to use it in a lib or so:

http://jsfiddle.net/mkzero/LumBj/10/

But thank you for pointing that out. Might come in handy some day.

over 1 year ago ·

@mkzero cool!

over 1 year ago ·

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside