I heard that Opera doesn't work with beforeunload. And some earlier versions of IE also. So how can I use these together ? If I use below, it runs 2 times (They all work) in Firefox.
$(window).bind('beforeunload', function () {
});
$(window).unload(function () {
});
I heard that Opera doesn't work with beforeunload. And some earlier versions of IE also. So how can I use these together ? If I use below, it runs 2 times (They all work) in Firefox.
$(window).bind('beforeunload', function () {
});
$(window).unload(function () {
});
Share
Improve this question
asked May 24, 2012 at 19:55
user198989user198989
4,66320 gold badges68 silver badges95 bronze badges
4 Answers
Reset to default 3There are several ways of doing this. Following example is quite straight forward using a global flag.
var hasUnloadBeenHandled = false;
function onUnload() {
if (hasUnloadBeenHandled) {
return;
}
//Whatever you want to be handled on unload OR on beforeunload
hasUnloadBeenHandled = true;
}
$(window).bind('beforeunload', function () {
onUnload();
});
$(window).unload(function () {
onUnload();
});
you need to use a flag of sort or you can use something like this http://documentcloud.github./underscore/#once
function unloadHandler(m){
alert(m);
}
if ($(window).unload) {
$(window).unload(function() {
unloadHandler("unload");
});
} else if ($(window).beforeunload) {
$(window).bind('beforeunload', function() {
unloadHandler("beforeunload");
});
}
Im not a Javascript/JQuery guy, but cant you just use a global variable to keep track of whether or not the method should run?
something like
var runme = true;
$(window).bind('beforeunload', function () {
if(runme){
runme=false;
}
});
$(window).unload(function () {
if(runme){
runme=false;
}
});