除非按下下一个或后退按钮,否则使用JS阻止页面重新加载?

时间:2015-03-02 15:05:52

标签: javascript jquery

我有页面重新加载提醒工作,但是当按下按钮时它们甚至会发生,因为这会触发页面重新加载。如果页面刷新,我将如何阻止页面重新加载并触发警报,除非按下按钮(输入类型为提交)

var dont_confirm_leave = 0; //set dont_confirm_leave to 1 when you want the user to be able to leave withou confirmation
var leaveMsg = "Dude, are you sure you want to leave? Think of the kittens!";

window.onbeforeunload = function() {

  if (window.location.href.indexOf("id=website") > -1 || window.location.href.indexOf("id=partner") > -1) {
    dont_confirm_leave = 1;
  }

  if (document.getElementsByClassName('NextBtn').onclick) {
    dont_confirm_leave = 1;
  }

  if (document.getElementsByClassName('BackBtn').onclick) {
    dont_confirm_leave = 1;
  }

  if (dont_confirm_leave !== 1) {
    if (!e) e = window.event;
    //e.cancelBubble is supported by IE - this will kill the bubbling process.
    e.cancelBubble = true;
    e.returnValue = leaveMsg;
    //e.stopPropagation works in Firefox.
    if (e.stopPropagation) {
      e.stopPropagation();
      e.preventDefault();
    }

    //return works for Chrome and Safari
    return leaveMsg;
  }
}

0 个答案:

没有答案