admin管理员组文章数量:1336129
I would like to prevent an HTML page refresh (given a variable refreshMode != 1
):
window.onbeforeunload = function(e) {
if(refreshMode == 1){
return;
}else{
// don't do it!
e.preventDefault();
}
};
I have tried e.preventDefault()
and e.stopPropagation()
, but neither appears to be preventing the refresh from submit the request.
Is it possible to do this?
I would like to prevent an HTML page refresh (given a variable refreshMode != 1
):
window.onbeforeunload = function(e) {
if(refreshMode == 1){
return;
}else{
// don't do it!
e.preventDefault();
}
};
I have tried e.preventDefault()
and e.stopPropagation()
, but neither appears to be preventing the refresh from submit the request.
Is it possible to do this?
Share Improve this question edited Jan 7, 2023 at 1:52 Paolo 21.2k21 gold badges76 silver badges121 bronze badges asked Aug 15, 2020 at 15:48 JimJim 2411 gold badge3 silver badges10 bronze badges 9- I have never done this by this way but there is others like using Ajax. If you are trying to do a one-page website I remend looking reactjs navigation. – Victor Molina Commented Aug 15, 2020 at 15:51
-
did you try
return false
? – Dominik Matis Commented Aug 15, 2020 at 15:52 -
Try
return true
: jsfiddle/ydbnuvt1 – Will Commented Aug 15, 2020 at 15:52 - 1 Does this answer your question? Prevent a webpage from navigating away using JavaScript – luk2302 Commented Aug 15, 2020 at 15:52
- e.preventDefault(); should work if you are handling the submit of a form through "onSubmit()", you doing that? – Menawer Commented Aug 15, 2020 at 15:58
1 Answer
Reset to default 4Set a return value in additiont o preventing default. You cannot change the prompt text (that used to be possible), and you cannot prevent the prefresh if the user confirms on the prompt.
See https://developer.mozilla/en-US/docs/Web/API/Window/beforeunload_event
window.addEventListener('beforeunload', (event) => {
// Cancel the event as stated by the standard.
event.preventDefault();
// Chrome requires returnValue to be set.
event.returnValue = '';
});
本文标签: How do I prevent a browser page refresh in JavaScriptStack Overflow
版权声明:本文标题:How do I prevent a browser page refresh in JavaScript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742348811a2458069.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论