问题
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