刷新页面时的JavaScript / PHP弹出窗口

时间:2015-09-17 10:33:56

标签: javascript

我有以下代码:

<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>

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

但是,如果单击“提交”按钮,如何阻止它运行弹出窗口?

1 个答案:

答案 0 :(得分:0)

这应该有效。请注意,您必须刷新要显示的消息的片段,但不要在单击按钮时显示。

&#13;
&#13;
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())
&#13;
<input type="button" value="SUBMIT" id="submit" />
&#13;
&#13;
&#13;