浏览器端 禁止 html 使用后退 或者替换后退功能..

时间:2021-07-18 22:30:27

知乎大佬的代码:

作者:独夜行
链接:https://www.zhihu.com/question/40511430/answer/166467343
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 (function() {
if (!window.history.pushState || !document.dispatchEvent) return;
var href = location.href;
var flag = true;
var voidFn = function() {};
var fn = voidFn;
var dispatchFn = function() {
var evt = document.createEvent('Event');
evt.initEvent('popstate',true,true);
window.dispatchEvent(evt);
}; // window.addEventListener('load', function() {
if (location.hash !== '#flag') {
history.replaceState({}, '', '/test02.html');
if (href.search('#') === -1) {
history.pushState({}, '', href + '#flag');
} else {
history.pushState({}, '', href.replace(/#.*/, '#flag'));
} } window.addEventListener('popstate', function() {
dispatchFn = voidFn;
flag = !flag;
if (flag) {
location.reload();
} // }, false); setTimeout(function() {
fn = dispatchFn;
fn();
}, 20);
}, false); })();

我的需求可能比较简单...仅仅是替换调回退 功能就ok了:

    (function () {
//页面加载完成 压入一个 历史记录...
history.pushState({}, '', '');
window.addEventListener('popstate', function (e) {
//console.log(e);
//父页面 关闭 所有layer 弹层...
parent.layer.closeAll();
//加上下面这句话后..永远不能跳转了---
//history.pushState({}, '', '');
}, false); })();