为了账号安全,请及时绑定邮箱和手机立即绑定

在浏览器中检测退按钮单击

在浏览器中检测退按钮单击

白衣非少年 2019-07-22 19:32:31
在浏览器中检测退按钮单击我必须检测用户是否单击了后退按钮。为此我用window.onbeforeunload = function (e) {}如果用户单击“后退”按钮,它就会工作。但是,如果用户单击浏览器的F5或重新加载按钮,也会触发此事件。我该怎么解决这个问题?
查看完整描述

3 回答

?
慕的地10843

TA贡献1785条经验 获得超8个赞

请尝试此操作(如果浏览器不支持“onpreunload”):

jQuery(document).ready(function($) {

  if (window.history && window.history.pushState) {

    $(window).on('popstate', function() {
      var hashLocation = location.hash;
      var hashSplit = hashLocation.split("#!/");
      var hashName = hashSplit[1];

      if (hashName !== '') {
        var hash = window.location.hash;
        if (hash === '') {
          alert('Back button was pressed.');
        }
      }
    });

    window.history.pushState('forward', null, './#forward');
  }});


查看完整回答
反对 回复 2019-07-22
?
当年话下

TA贡献1890条经验 获得超9个赞

我知道最好的方法

         window.onbeforeunload = function (e) {
            var e = e || window.event;
            var msg = "Do you really want to leave this page?"

            // For IE and Firefox
            if (e) {
                e.returnValue = msg;
            }

            // For Safari / chrome
            return msg;
         };


查看完整回答
反对 回复 2019-07-22
  • 3 回答
  • 0 关注
  • 345 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信