Call a function on page refresh using Javascript

谁说我不能喝 提交于 2019-12-22 10:57:26

问题


function warnuser()
{
    return "Don't refresh the page.";
}

window.onbeforeunload = warnuser;

If the user refreshes the page and the user clicks 'leave this page' on confirmation box, i want to call a javascript function , otherwise not! I am confused about how to do that. Thank you


回答1:


You need to intercept the F5 key press and setup the onbeforeunload handler only in that case:

document.addEventListener('keydown', function(e) {
    if(e.which == 116) {
        window.onbeforeunload = function() {
            window.onbeforeunload = null;
            return "Do you really want to refresh the page?";
        }
    }
}, false);

Demo: http://jsfiddle.net/ejDrq/

Note that this does not work if the user clicks the Refresh button. It is impossible to intercept this.




回答2:


If you have control of the server side which is hosting the page then you can handle this logically with a semaphore (wiki:semaphore). Basically it is a spinning lock which would be implemented in their server side session. Resetting the page state if they have entered and not exited in a safe manner. Naturally, as with all spinning locks, there would have to be a safe state to clear the lock out.



来源:https://stackoverflow.com/questions/11285908/call-a-function-on-page-refresh-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!