在卸载功能之前,在窗口中单击“重新加载”按钮从JavaScript调用函数?

时间:2017-04-18 11:45:37

标签: javascript jquery

我在JavaScript中有一个函数,在单击关闭或刷新按钮时执行。

$(window).bind("beforeunload",function(event) {
            return "Save or Not";
    }
});

当我点击刷新按钮(重新加载并且不在Chrome中重新加载)时,这会弹出一个有2个按钮的弹出按钮。现在我想调用一个函数重定向到我的主页,如果我点击重新加载按钮。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

请试试这个

  $(document).ready(function() {


      setTimeout(function() {

      var __redirect_to = 'url_where_to_send';//

      var _tags = ['button', 'input', 'a'], _els, _i, _i2;

      for(_i in _tags) {

          _els = document.getElementsByTagName(_tags[_i]);

          for(_i2 in _els) {

              if((_tags[_i] == 'input' && _els[_i2].type != 'button' && _els[_i2].type != 'submit' && _els[_i2].type != 'image') || _els[_i2].target == '_blank') continue;

              _els[_i2].onclick = function() {window.onbeforeunload = function(){};}

          }

     }

      window.onbeforeunload = function() {

          setTimeout(function() {

              window.onbeforeunload = function() {};

              setTimeout(function() {

                  document.location.href = __redirect_to;

              }, 500);

          },5);

          return 'Are you sure you want to leave this page?\n\nWait...Before you go:\n\n***************************************\n\n GET A FREE BOTTLE OF NeuroNZT\n\n***************************************\n\nTo receive your bottle FOR FREE - Click Cancel or Stay on Page below';

      }

      }, 500);

  });

  </script>