最靠谱的方式是通过JS监控popstate事件,然后进行相应的处理。核心代码如下:
if (window.history && window.history.pushState) {
//document.addEventListener('visibilitychange', function() {
// alert(document.visibilityState);
//}, false);
//window.on('popstate', function() {
// alert("我监听到了浏览器的popstate");
//});
//window.onpopstate = function(e) {
// console.log(e.state);
//
//};
$$(window).on('popstate', function() { // 返回按钮
var hashLocation = location.hash; // 获取或设置页面的标签值
console.log("popstate");
console.log("hashLocation:"+hashLocation);
var hashSplit = hashLocation.split("#!/");
var hashName = hashSplit[1];
console.log("hashName:"+hashLocation);
if (hashName !== '') {
var hash = window.location.hash; // 获取或设置页面的标签值
console.log("hash:"+hash);
if (hash === '') {
alert('再次点击返回按钮退出程序');
}
}
});
console.log("pushstate");
var url = window.location.href;
var timestamp = new Date().getTime();
if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
window.history.pushState('forward', null, './#forward');
} else {
window.history.pushState('', "大糖医", url+"#"+timestamp); // 状态对象、标题(现在会被忽略),可选的URL地址。
}
}