防止页面后退(使浏览器后退按钮失效)

原理:用新页面的URL替换当前的历史纪录,这样浏览历史记录中就只有一个页面,后退按钮永远失效。

注:history.go和history.back(包括用户按浏览器历史前进后退按钮)触发,

页面由于使用pushState修改了history,会触发popstate事件。

方法一:

jQuery(document).ready(function ($) {
                if (window.history && window.history.pushState) {
        $(window).on('popstate', function () {
            window.history.forward(1);
        });
      }
});

方法二【推荐】:

$(function() {
if (window.history && window.history.pushState) {
$(window).on('popstate', function () {
window.history.pushState('forward', null, '#');
window.history.forward(1);
});
}
window.history.pushState('forward', null, '#'); //在IE中必须得有这两行
window.history.forward(1);
})
//控制浏览器和移动端的后退按钮
          if (window.history && window.history.pushState) {
            $(window).on('popstate', function () {
              var block1 = $('#pop').css('display');
              if (block1 == 'block') {
                window.location.href = attrHref;
              }
              var hashLocation = location.hash;
              var hashSplit = hashLocation.split("#!/");
              var hashName = hashSplit[1];
              if (hashName !== '') {
                var hash = window.location.hash;
                if (hash === '') {
                  popBox.style.display = 'none'
                  popSub.style.display = 'block'
                }
              }
            });
            history.pushState(null, null, location.href);
            window.addEventListener('popstate', function (event) {
              history.pushState(null, null, location.href);
            });
          }
window. history.forward() --- 此方法加载历史列表中的下一个 URL,同浏览器中点击向前按钮;
window. history.back() --- 此方法加载历史列表中的前一个 URL,同浏览器中点击后退按钮。
window.history.pushState(null, "", "#/tieOnCardPage") //这是你想 返回的 页面
window.history.pushState(null, "", "#/setPasswordPage") //这是本页面


如果你依然在编程的世界里迷茫,不知道自己的未来规划,可以加入前端学习进阶内推交流群685910553前端资料分享)。里面可以与大神一起交流并走出迷茫。

新手可免费领取学习资料,看看前辈们是如何在编程的世界里傲然前行不停更新最新的教程和学习方法(详细的前端项目实战教学视频),

有想学习web前端的,或是转行,或是大学生,还有工作中想提升自己能力的,正在学习的小伙伴欢迎加入