最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using beforeunload and unload together? - Stack Overflow

programmeradmin7浏览0评论

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
Add a ment  | 

4 Answers 4

Reset to default 3

There 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;
    }
});
发布评论

评论列表(0)

  1. 暂无评论