我想用JavaScript看是否有历史记录,后退按钮在浏览器上是否可用。
当前回答
我用的是window。在我的网站上的常见问题解答。
当用户想退出FAQ时,他们可以点击退出按钮(在后退按钮旁边)
我对这个“退出”策略的逻辑是基于入口ID,然后返回到该状态的状态数。
所以进入:
enterState: { navigationId:number } = {navigationId: 1}
constructor() {
this.enterState = window.history.state
}
假设用户正在浏览FAQ
然后,当用户单击退出按钮时,读取当前状态并计算delta:
exitFaq() {
// when user started in faq, go back to first state, replace it with home and navigate
if (this.enterState.navigationId === 1) {
window.history.go((window.history.state.navigationId - 1) * -1)
this.router.navigateByUrl('/')
// non-angular
// const obj = {Title: 'Home', Url: '/'}
// window.history.replaceState(obj, obj.Title, obj.Url)
} else {
window.history.go(this.enterState.navigationId - window.history.state.navigationId - 1)
}
}
如你所见,我还使用了一个回退当用户开始在faq,在这种情况下,状态。navigationId为1,我们想要路由回去,替换第一个状态,并显示主页(为此我使用Angular路由器,但你也可以使用历史记录。当你处理自己的路由时,也可以使用replaceState)
供参考:
history.go history.state history.replaceState Angular.router.navigateByUrl
其他回答
这可能会有帮助:
const prev = window.location.pathname;
window.history.back();
setTimeout(() => {
if (prev === window.location.pathname) {
// Do something else ...
}
}, 1000);
var fallbackUrl = "home.php";
if(history.back() === undefined)
window.location.href = fallbackUrl;
这似乎很管用:
function goBackOrClose() {
window.history.back();
window.close();
//or if you are not interested in closing the window, do something else here
//e.g.
theBrowserCantGoBack();
}
调用history.back(),然后调用window.close()。如果浏览器能够返回历史记录,它将无法到达下一条语句。如果无法返回,就会关闭窗口。
但是,请注意,如果已经通过输入url到达页面,那么firefox不允许脚本关闭窗口。
这是我的解决方案:
function historyBack() {
console.log('back');
window.history.back() || window.history.go(-1);
if (!window.history.length) window.close();
var currentUrl = window.location.href;
setTimeout(function(){
// if location was not changed in 100 ms, then there is no history back
if(current === window.location.href){
console.log('History back is empty!');
}
}, 100);
}
function historyForward() {
console.log('forward');
window.history.forward() || window.history.go(+1);
var current = window.location.href;
setTimeout(function(){
// if location was not changed in 100 ms, then there is no history forward
if(current === window.location.href){
console.log('History forward is empty!');
}
}, 100);
}
这工作为我使用react,但可以在另一种情况下工作;当历史记录在第一页时(你不能返回)window.history.state将为null,所以如果你想知道你是否可以返回,你只需要:
if (window.history.state == null) {
//you cannot go back
}
文档:
的历史。状态属性返回表示位于的状态的值 历史堆栈的顶端。这是一种看待国家的方式 而不必等待popstate事件。