我想用JavaScript看是否有历史记录,后退按钮在浏览器上是否可用。


当前回答

var func = function(){ console.log("do something"); };
if(document.referrer.includes(window.location.hostname) && history.length-1 <= 1){
    func();
}
else{
    const currentUrl = window.location.href;
    history.back();
    setTimeout(function(){
        currentUrl === window.location.href && func();
    }, 100);
}

其他回答

你不能直接检查后退按钮是否可用。你可以看看历史。长度为>0,但如果在当前页之前还有页,这也是成立的。只有当history.length===0时,才能确定后退按钮不可用。

如果这还不够好,你所能做的就是调用history.back(),如果你的页面之后仍然被加载,返回按钮是不可用的!当然,这意味着如果后退按钮可用,则您刚刚导航离开了页面。你不允许取消onunload中的导航,所以你所能做的就是从onbeforeunload中返回一些东西,这将导致一个恼人的大提示符出现。这不值得。

事实上,用历史做任何事情通常都是一个非常糟糕的主意。历史导航是chrome浏览器,不是网页。添加“返回”链接通常会引起更多用户的困惑,而不是它的价值。

还有另一个近乎完美的解决方案,来自于另一个SO答案:

if( (1 < history.length) && document.referrer ) {
    history.back();
}
else {
    // If you can't go back in history, you could perhaps close the window ?
    window.close();
}

有人报告说,当使用target="_blank"时,它不工作,但它似乎在Chrome上为我工作。

var func = function(){ console.log("do something"); };
if(document.referrer.includes(window.location.hostname) && history.length-1 <= 1){
    func();
}
else{
    const currentUrl = window.location.href;
    history.back();
    setTimeout(function(){
        currentUrl === window.location.href && func();
    }, 100);
}

检查window.history.length是否等于0。

以这里和这里的答案为基础。我认为,更确切的答案是检查这是否是一个新标签中的新页面。

如果页面的历史记录不止一个,那么我们可以返回到当前页面之前的页面。如果不是,则该标签是新打开的标签,我们需要创建一个新标签。

不同的是,对于链接的答案,我们不会检查一个推荐人,因为一个新的标签仍然会有一个推荐人。

if(1 < history.length) {
    history.back();
}
else {
    window.close();
}