简体   繁体   中英

onbeforeunload is executed once only

I use onbeforeunload to reset a variable with Ajax request. But it is executed once only. Eg if I visit the page (after log in) and close the window, the function is executed, but if I repeat the operation (putting the address in the browser with login done and closing the window) the function isn't executed.

window.onbeforeunload = function (e) {
    //Ajax request to reset variable in database 
    resetDemoValueWithAjax();
};

//Ajax request to reset variable in database and exit
function resetDemoValueWithAjax(){
    $.ajax({
        async:true,
        type: "POST",
        dataType: "json",  
        url:"http://localhost/site/index.php/welcome/resetDemoValue",
        data: {name: "demo"},
        success:function(){
            document.location.href='http://localhost/site/index.php/auth/logout';   
        },
        error: function(){
            document.location.href='http://localhost/site/index.php/auth/logout';   
        } 
    });     
}

document.location.href='http://localhost/site/index.php/auth/logout'; Only is used in another moment: When the user does logout. Not here

You have a race condition . The race is between the asynchronous Ajax request and the browser's attempt to navigate away from the page (which is what caused beforeunload in the first place). The navigation away will probably always win, so the browser moves away from the page before the Ajax callback can complete.

If you made the Ajax request synchronous with async:false , this race wouldn't happen, since the JavaScript thread would block until the Ajax request resolved. Be aware that this makes for a potentially annoying user experience (ie, the user tries to close the page but has to wait for the Ajax request to resolve before the tab will close).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM