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.
Written by Kushagra Gour
Related protips
3 Responses
Just forked your script :)
http://jsfiddle.net/yM5n5/1/
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.
@mkzero cool!
Have a fresh tip? Share with Coderwall community!
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