如何防止在JavaScript中刷新浏览器页面

时间:2020-08-15 15:48:58

标签: javascript page-refresh

我想防止HTML页面刷新(给定refreshMode变量!= 1):

window.onbeforeunload = function(e) {
   if(refreshMode == 1){
     return;
   }else{
     // don't do it!
    e.preventDefault();
   }
};

我尝试了e.preventDefault()和e.stopPropagation(),但似乎都不能阻止刷新提交请求。

可以这样做吗?

1 个答案:

答案 0 :(得分:1)

另外设置返回值以防止默认值。您无法更改提示文本(以前可能这样),并且如果用户在提示上确认,也无法阻止刷新。

请参见https://developer.mozilla.org/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 = '';
});