使用Javascript在页面刷新时调用函数(Call a function on page refresh using Javascript)
function warnuser()
{
return "Don't refresh the page.";
}
window.onbeforeunload = warnuser;
如果用户刷新页面并且用户在确认框上单击“离开此页面”,我想调用javascript函数,否则不会! 我很困惑如何做到这一点。 谢谢
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
最满意答案
您需要拦截F5键按下并仅在这种情况下设置onbeforeunload处理程序:
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);演示: http : //jsfiddle.net/ejDrq/
请注意,如果用户单击 “刷新”按钮,则不起作用。 拦截这个是不可能的。
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.
更多推荐
发布评论