最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How do I prevent a browser page refresh in JavaScript? - Stack Overflow

programmeradmin0浏览0评论

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
 |  Show 4 more ments

1 Answer 1

Reset to default 4

Set 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 = '';
});
发布评论

评论列表(0)

  1. 暂无评论