使用Javascript在页面刷新时调用函数(Call a function on page refresh using Javascript)

编程入门 行业动态 更新时间:2024-10-19 23:35:19
使用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.

更多推荐

本文发布于:2023-08-01 01:20:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1350581.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时调   函数   页面   Javascript   refresh

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!