我有一个类似单页网络应用程序的东西。为了处理用户单击后退按钮,我使用“popstate”事件
这是:
window.addEventListener('popstate', function () {
backOneStep(0); // do my own job (get user to previous application screen)
history.pushState(null, null, '');
});
在 Firefox 和 Safari 中,该事件运行良好。当用户按下“后退”按钮时 -
backOneStep
被执行
很长一段时间一切都很好,但是!但在 Chrome 中,最新更新后,如果之前的
popstate
调用是从代码发起的,则 history.pushState
事件不会触发
所以: 如果您按一次后退按钮,您将发现应用程序返回一个屏幕。
如果您第二次按下该按钮,您将被踢出我的申请:(
让我感到困惑的是 - 如果您在第二次单击之前单击页面上的任意位置,该事件也会再次触发
我做了一个简单的例子 -
<button id="test">Click</button>
<div id="info"></div>
Javascript:
var populate=document.getElementById("test");
/*Initiate custom history*/
var myHistory=[{URL: location.href}];
function pushState_(data, pageUrl, pageTitle){
pageUrl=pageUrl||location.href;
data["URL"]=pageUrl;
window.history.pushState(data, pageTitle||"My Page", pageUrl);
//Push to custom history
myHistory.push(data);
}
let backPressed=0;
let popstateData={};
window.addEventListener("popstate", function (event) {
let totalHistory=myHistory.length;
if( totalHistory==0){
//Exit browser
history.back();
history.pushState(null, null, window.location.pathname);
return;
}
if( backPressed) {
// Your page state logic here:
//go_onBackPressed( popstateData );
window.history.replaceState(popstateData, null, popstateData.URL );
backPressed=0;
return;
}
if( totalHistory){
myHistory.pop();
popstateData=myHistory[myHistory.length-1];
}
backPressed++;
window.history.replaceState(null, null, location.pathname );
window.history.forward();
});
let test=0;
populate.addEventListener('click', () => {
pushState_({data:1});
var div = document.getElementById('info');
test++;
div.innerHTML += "<br>Pushed count: " + test;
});