Javascript 如何检查用户是否可以返回浏览器历史记录

Javascript 如何检查用户是否可以返回浏览器历史记录,javascript,Javascript,我想使用JavaScript查看是否有历史记录,我的意思是浏览器上是否有“后退”按钮。我不确定这是否有效,它完全未经测试,但请尝试以下方法: <script type="text/javascript"> function goBack() { history.back(); } if (history.length > 0) { //if there is a history... document.getEleme

我想使用JavaScript查看是否有历史记录,我的意思是浏览器上是否有“后退”按钮。

我不确定这是否有效,它完全未经测试,但请尝试以下方法:

<script type="text/javascript">

    function goBack() {
        history.back();
    }

    if (history.length > 0) { //if there is a history...
        document.getElementsByTagName('button')[].onclick="goBack()"; //assign function "goBack()" to all buttons onClick
    } else {
        die();
    }
</script>

函数goBack(){
历史。返回();
}
如果(history.length>0){//如果有历史记录。。。
document.getElementsByTagName('button')[].onclick=“goBack()”;//将函数“goBack()”分配给所有按钮onclick
}否则{
模具();
}
在HTML中的某个地方:

<button value="Button1"> //These buttons have no action
<button value="Button2">
//这些按钮没有任何操作
编辑:
您还可以研究哪些浏览器支持back函数(我认为它们都支持),并使用在上找到并详细描述的标准JavaScript浏览器检测对象。然后,您可以有两个不同的页面:一个用于与“后退”按钮兼容的“好浏览器”,另一个用于“坏浏览器”,告诉他们去更新浏览器

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

您不能直接检查“后退”按钮是否可用。您可以查看
history.length>0
,但如果当前页面前面也有页面,则这一点也适用。只有当
history.length==0
时,才能确保“后退”按钮不可用

如果这还不够好,那么您所能做的就是调用
history.back()
,如果您的页面在加载之后仍然处于加载状态,则“后退”按钮不可用!当然,这意味着如果“后退”按钮可用,则您已经离开了页面。您不允许取消
onunload
中的导航,因此您所能做的只是从
onbeforeuload
返回一些内容,这将导致出现一个大的恼人提示。这不值得


事实上,对历史做任何事情通常都是个糟糕的主意。历史导航是针对浏览器chrome的,而不是网页。添加“返回”链接通常会给用户带来更多的困惑。

简短回答:你不能

从技术上讲,有一种准确的方法,即检查财产:

history.previous
但是,它不起作用。问题是,在大多数浏览器中,这被视为安全违规,通常只返回未定义的

history.length
是其他人建议的财产…
然而,长度并不完全起作用,因为它不表示您在历史记录中的位置。此外,它并不总是从同一个数字开始。例如,未设置为具有登录页的浏览器将从0开始,而另一个使用登录页的浏览器将从1开始

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

history.back();


如果你不能返回,点击链接什么也做不了。

还有另一种检查方法——检查推荐人。第一页通常会有一个空的推荐人

if (document.referrer == "") {
    window.close()
} else {
    history.back()
}

这似乎起到了作用:

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将不允许脚本关闭窗口。

我的代码允许浏览器返回一个页面,如果失败,则加载一个备用url。它还检测hashtags的变化

当“后退”按钮不可用时,回退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);
}
我是这样做的

我使用“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)。

历史记录。长度是无用的,因为它不能显示用户是否可以回到历史记录中。
此外,不同的浏览器使用初始值0或1-这取决于浏览器

有效的解决方案是使用
$(window).on('beforeunload'
事件),但如果页面通过ajax加载并使用pushState更改窗口历史记录,我不确定它是否有效

$(window).load(function() {
        if (window.history.length == 1) {
            $("#back-button").remove();
        }
    })
所以我使用了下一个解决方案:

var currentUrl = window.location.href;
window.history.back();
setTimeout(function(){
    // if location was not changed in 100 ms, then there is no history back
    if(currentUrl === window.location.href){
        // redirect to site root
        window.location.href = '/';
    }
}, 100);

小心使用
window.history.length
,因为它还包括
window.history.forward()的条目

因此,您可能有超过1个条目的
window.history.length
,但没有历史回溯条目。
这意味着,如果启动
window.history.back()

则不会发生任何事情。我在项目中使用了一个片段:

function back(url) {
    if (history.length > 2) {
        // if history is not empty, go back:
        window.History.back();
    } else if (url) {
        // go to specified fallback url:
        window.History.replaceState(null, null, url);
    } else {
        // go home:
        window.History.replaceState(null, null, '/');
    }
}
仅供参考:我用于管理浏览器历史记录


为什么要将history.length与数字2进行比较?

因为Chrome的startpage被视为浏览器历史记录中的第一项


历史记录的可能性很小。长度和用户行为:

  • 用户在浏览器中打开新的空选项卡,然后运行一个页面。
    history.length=2
    在这种情况下,我们希望禁用
    back()
    ,因为用户将转到空选项卡
  • 用户通过单击之前某个位置的链接,在新选项卡中打开页面。
    history.length=1
    ,我们再次希望禁用
    back()
    方法
  • 最后,用户在重新加载几页
    history.length>2
    后到达当前页面,现在可以启用
    back()

注意:当用户在没有
target=“\u blank”
的情况下单击外部网站的链接后到达当前页面时,我省略了大小写

注2:
文档。当您
function back(url) {
    if (history.length > 2) {
        // if history is not empty, go back:
        window.History.back();
    } else if (url) {
        // go to specified fallback url:
        window.History.replaceState(null, null, url);
    } else {
        // go home:
        window.History.replaceState(null, null, '/');
    }
}
var goBack = function goBack(fallback){
    var useFallback = true;

    window.addEventListener("beforeunload", function(){
      useFallback = false;
    });

    window.history.back();

    setTimeout(function(){
        if (useFallback){ window.location.href = fallback; }
    }, 100); 
}
  location.href = '#__transfer__' + new Date().getTime() 
  var realHistoryLength = history.length - 1
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();
}
'use strict';
function previousPage() {
  if (window.location.pathname.split('/').filter(({ length }) => length > 0).length > 0) {
    window.history.back();
  }
}
'use strict';
window.location.pathname.split('/').filter(function(fragment) {
  return fragment.length > 0;
});
'use strict';
function previousPage() {
  if (window.location.pathname.split('/').filter(({ length }) => length > 0).length > 0) {
    window.history.back();
  } else {
    alert('You cannot go back any further...');
  }
}
if(1 < history.length) {
    history.back();
}
else {
    window.close();
}
$(window).load(function() {
        if (window.history.length == 1) {
            $("#back-button").remove();
        }
    })
<?php 
function pref(){ 
  return (isset($_SERVER['HTTP_REFERER'])) ? true : '';
}
?>
<html>
<body>

<input type="hidden" id="_pref" value="<?=pref()?>">

<button type="button" id="myButton">GoBack</button>

<!-- Include jquery library -->
<script> 
  if (!$('#_pref').val()) { 
    $('#myButton').hide() // or $('#myButton').remove()
  } 
</script>
</body>
</html>
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);
}