JS监听手机返回键,需要用些前端的“奇技淫巧”。
核心代码如下:
if (window.history && window.history.pushState)
{ $(window).on('popstate', function() { var hashLocation = location.hash; var hashSplit = hashLocation.split("#!/");
var hashName = hashSplit[1];
if (hashName !== '') { var hash = window.location.hash; if (hash === '') { alert('後退按鈕點擊'); } } });
window.history.pushState('forward', null, './#forward');
}
//监听手机返回键
if (window.history && window.history.pushState) {
$(window).on('popstate', function () {
var hash = window.location.hash;
if (hash === '') {
goForback();//返回
window.history.pushState('forward', null, 'homePage.html');//注意homePage.html是返回路径(继续监听)
}
});
window.history.pushState('forward', null, '');//注意homePage.html是返回路径
}