admin管理员组文章数量:1303537
I'm using onbeforeunload
event to perform operations during the closing page.
I do not want the event to happen in the case of Refresh
/ F5.
Is there a way or other event to do this?
I'm using onbeforeunload
event to perform operations during the closing page.
I do not want the event to happen in the case of Refresh
/ F5.
Is there a way or other event to do this?
Share Improve this question edited May 26, 2016 at 12:53 Refael asked Oct 23, 2013 at 8:10 RefaelRefael 7,35310 gold badges38 silver badges54 bronze badges3 Answers
Reset to default 4Unfortunately onbeforeunload
event listens the page state in the browser. Going to another page as well as refreshing will change the page state, meaning onbeforeunload
will be triggered anyway.
So I think it is not possible to catch only refresh.
But, if you'll listen and prevent Keypress
via JavaScript, then it can be achieved.
Refresh can be done via F5 and CtrlR keys, so your goal will be to prevent these actions.
using jQuery .keydown() you can detect these keycodes:
For CtrlR
$(document).keydown(function (e) {
if (e.keyCode == 65 && e.ctrlKey) {
e.preventDefault();
}
});
For F5
$(document).keydown(function (e) {
if (e.which || e.keyCode) == 116) {
e.preventDefault();
}
});
I would use the keydown listener to check for F5 and set a flag var.
http://api.jquery./keydown/
Detecting refresh with browser button is not that easy/possible.
I wanted to add a message alert onbeforeunload, so my solution was this one:
$(document).ready(function(){
window.onbeforeunload = PopIt;
$("a").click(function(){ window.onbeforeunload = UnPopIt; });
$(document).keydown(function(e){
if ((e.keyCode == 82 && e.ctrlKey) || (e.keyCode == 116)) {
window.onbeforeunload = UnPopIt;
}
});
});
function PopIt() { return "My message before leaving"; }
function UnPopIt() { /* nothing to return */ }
Third line ($("a").click...) is to avoid showing the alert when navigating between sections of the web.
本文标签: javascriptprevent OnBeforeUnload() event from happening in refreshF5Stack Overflow
版权声明:本文标题:javascript - prevent OnBeforeUnload() event from happening in refreshF5 - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741745592a2395512.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论