在Chrome上禁用后退按钮历史记录不起作用

问题描述 投票:0回答:1

为了安全起见,我想通过使用此JavaScript代码在我的应用程序网站中禁用某些页面,该代码在其他浏览器中也可以正常使用:

history.pushState(null, null, location.href);
window.onpopstate = function () {
    history.go(1);
};

但不幸的是,在chrome浏览器中,除非用户在页面上或在控制台的开发人员工具中单击(如果您在其中运行任何javascript,例如这样的代码),否则此代码不会激活:

console.log('test');

自动启用后退按钮Chrome浏览器。我发现此页面上早已讨论过此问题:Google Chrome Help

javascript google-chrome browser
1个回答
0
投票
(function (global) {

if(typeof (global) === "undefined") {
  throw new Error("window is undefined");
}

var _hash = "!";
var noBackPlease = function () {
 global.location.href += "#";
 global.setTimeout(function () {
   global.location.href += "!";
 }, 50);
};

global.onhashchange = function () {
 if (global.location.hash !== _hash) {
   global.location.hash = _hash;
 }
};

global.onload = function () {
 noBackPlease();

// disables backspace on page except on input fields and textarea..
document.body.onkeydown = function (e) {
 var elm = e.target.nodeName.toLowerCase();
  if (e.which === 8 && (elm !== 'input' && elm  !== 'textarea')) {
     e.preventDefault();
  }
  // stopping event bubbling up the DOM tree..
  e.stopPropagation();
 };
}

})(window);

history.pushState(null, document.title, location.href);
window.addEventListener('popstate', function (event)
{
history.pushState(null, document.title, location.href);
});

window.location.hash="no-back-button";
window.location.hash="Again-No-back-button";//again because google chrome don't insert first hash into history
window.onhashchange=function(){window.location.hash="no-back-button";}
© www.soinside.com 2019 - 2024. All rights reserved.