JavaScript/PHP刷新页面时弹出

JavaScript/PHP Popup when Refreshing Page

本文关键字:PHP 刷新 JavaScript      更新时间:2023-09-26

我有以下代码:

<script>
    var myEvent = window.attachEvent || window.addEventListener;
    var chkevent = window.attachEvent ? 'onbeforeunload' : 'beforeunload';
    myEvent(chkevent, function(e) {
        var confirmationMessage = 'HELLO';
        (e || window.event).returnValue = confirmationMessage;
        return confirmationMessage;
    });
</script>

当用户尝试刷新脚本所运行的页面时,将运行一个小的弹出框。

但是,如果他们点击提交按钮,我如何阻止它运行弹出窗口呢?

应该可以。请注意,您必须刷新代码片段才能显示您的消息,而不是在单击按钮时刷新。

var myEvent = window.attachEvent || window.addEventListener;
var chkevent = window.attachEvent ? 'onbeforeunload' : 'beforeunload';
var unloading = true;
myEvent(chkevent, function(e) {
  if(!unloading) return;
  var confirmationMessage = 'HELLO';
  (e || window.event).returnValue = confirmationMessage;
  return confirmationMessage;
});
document.getElementById('submit').addEventListener('click', function(e){
  unloading = false;
  // Because this button does nothing, the reload will load an empty page in SO
  // However, note there is no beforeunload event actioned.
  location.reload();
});
document.write('Current Time: ' + Date.now())
<input type="button" value="SUBMIT" id="submit" />