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


当前回答

我是这样做的。

我使用'beforeunload'事件来设置一个布尔值。然后我设置了一个超时来观察“beforeunload”是否被触发。

var $window = $(window),
    $trigger = $('.select_your_link'),
    fallback = 'your_fallback_url';
    hasHistory = false;

$window.on('beforeunload', function(){
    hasHistory = true;
});

$trigger.on('click', function(){

    window.history.go(-1);

    setTimeout(function(){
        if (!hasHistory){
            window.location.href = fallback;
        }
    }, 200);

    return false;
});

似乎在主要的浏览器(测试FF, Chrome, IE11到目前为止)。

其他回答

var fallbackUrl = "home.php";
if(history.back() === undefined)
    window.location.href = fallbackUrl;

我试图找到一个解决方案,这是我能得到的最好的(但工作很棒,这是我在这里找到的最简单的解决方案)。

在我的情况下,我想回到历史上一个返回按钮,但如果用户打开的第一页是我的应用程序的子页,它会回到主页。

解决方案是,一旦应用程序被加载,我只是做了一个替换历史状态:

history.replaceState( {root: true}, '', window.location.pathname + window.location.hash)

这样,我只需要在返回之前检查history.state.root。如果是真的,我做一个历史代替:

if(history.state && history.state.root)
    history.replaceState( {root: true}, '', '/')
else
    history.back() 

这是我的解决方案:

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);
}

简单的回答:你不能。

技术上有一个准确的方法,那就是检查属性:

history.previous

然而,这是行不通的。这样做的问题是,在大多数浏览器中,这被认为是违反安全的,通常只是返回undefined。

history.length

是其他人认为的… 然而,长度并不能完全起作用,因为它不能表明你所处的历史位置。此外,它并不总是从相同的数字开始。例如,一个未设置有登录页的浏览器将从0开始,而另一个使用登录页的浏览器将从1开始。

大多数情况下,添加的链接调用:

history.back();

or

 history.go(-1);

如果你不能返回,那么点击链接就没有任何作用。

我的代码让浏览器返回一个页面,如果失败,它加载一个回退url。它还可以检测标签的变化。

当后退按钮不可用时,回退url将在500毫秒后加载,这样浏览器就有足够的时间加载上一页。在window.history.go(-1)之后加载回退url;会导致浏览器使用回退url,因为js脚本还没有停止。

function historyBackWFallback(fallbackUrl) {
    fallbackUrl = fallbackUrl || '/';
    var prevPage = window.location.href;

    window.history.go(-1);

    setTimeout(function(){ 
        if (window.location.href == prevPage) {
            window.location.href = fallbackUrl; 
        }
    }, 500);
}