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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3588315/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:19:32  来源:igfitidea点击:

How to check if the user can go back in browser history or not

javascript

提问by Ryan

I want using JavaScript to see if there is history or not, I mean if the back button is available on the browser or not.

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

采纳答案by McAden

Short answer: You can't.

简短的回答:你不能。

Technically there is an accurate way, which would be checking the property:

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

history.previous

However, it won't work.The problem with this is that in most browsers this is considered a security violation and usually just returns undefined.

但是,它不会起作用。这样做的问题是,在大多数浏览器中,这被视为违反安全性,通常只返回undefined

history.length

Is a property that others have suggested...
However, the length doesn't work completely because it doesn't indicate wherein the history you are. Additionally, it doesn't always start at the same number. A browser not set to have a landing page, for example, starts at 0 while another browser that uses a landing page will start at 1.

是一个属性,其他人已经建议......
但是,长度不完全,因为它并不表示工作地方在历史上你。此外,它并不总是从相同的数字开始。例如,一个没有设置登陆页面的浏览器从 0 开始,而另一个使用登陆页面的浏览器将从 1 开始。

alt text

替代文字

Most of the time a link is added that calls:

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

history.back();

or

或者

 history.go(-1);

and it's just expected that if you can't go back then clicking the link does nothing.

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

回答by Ron Reiter

There is another way to check - check the referrer. The first page usually will have an empty referrer...

还有另一种检查方法 - 检查推荐人。第一个页面通常会有一个空的引用...

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

回答by redelschaap

My code let the browser go back one page, and if that fails it loads a fallback url. It also detect hashtags changes.

我的代码让浏览器返回一页,如果失败,它会加载一个后备 url。它还检测主题标签的变化。

When the back button wasn't available, the fallback url will be loaded after 500 ms, so the browser has time enough to load the previous page. Loading the fallback url right after window.history.go(-1);would cause the browser to use the fallback url, because the js script didn't stop yet.

当后退按钮不可用时,回退 url 将在 500 毫秒后加载,因此浏览器有足够的时间加载上一页。立即加载回退 urlwindow.history.go(-1);会导致浏览器使用回退 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);
}

回答by gregmatys

There is a snippet I use in my projects:

我在我的项目中使用了一个片段:

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, '/');
    }
}

FYI: I use History.jsto manage browser history.

仅供参考:我使用History.js来管理浏览器历史记录。



Why to compare history.length to number 2?

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

Because Chrome's startpage is counted as first item in the browser's history.

因为 Chrome 的起始页被视为浏览器历史记录中的第一项。



There are few possibilities of history.lengthand user's behaviour:

history.length用户行为的可能性很少:

  • User opens new empty tabin the browser and then runs a page. history.length = 2and we want to disable back()in this case, because user will go to empty tab.
  • User opens the page in new tabby clicking a link somewhere before. history.length = 1and again we want to disable back()method.
  • And finally, user lands at current page after reloading few pages. history.length > 2and now back()can be enabled.
  • 用户在浏览器中打开新的空标签,然后运行一个页面。history.length = 2我们想back()在这种情况下禁用,因为用户将转到空选项卡。
  • 用户通过单击之前某处的链接在新选项卡中打开页面。history.length = 1我们再次想禁用back()方法。
  • 最后,用户在重新加载几页后登陆当前页面history.length > 2现在back()可以启用了。


Note:I omit case when user lands at current page after clicking link from external website without target="_blank".

注意:当用户点击外部网站的链接后,在没有target="_blank".

Note 2:document.referreris empty when you open website by typing its address and also when website uses ajax to load subpages, so I discontinued checking this value in the first case.

注 2:document.referrer当您通过键入地址打开网站以及网站使用 ajax 加载子页面时为空,因此我在第一种情况下不再检查此值。

回答by Toni Feistauer

Here is how i did it.

这是我如何做到的。

I used the 'beforeunload' eventto set a boolean. Then I set a timeout to watch if the 'beforeunload' fired.

我使用'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;
});

Seems to work in major browsers (tested FF, Chrome, IE11 so far).

似乎适用于主要浏览器(到目前为止已测试 FF、Chrome、IE11)。

回答by xtrahelp.com

this seems to do the trick:

这似乎可以解决问题:

function goBackOrClose() {  

    window.history.back();
    window.close(); 

    //or if you are not interested in closing the window, do something else here
    //e.g. 
    theBrowserCantGoBack();

}

Call history.back() and then window.close(). If the browser is able to go back in history it won't be able to get to the next statement. If it's not able to go back, it'll close the window.

调用 history.back() 然后调用 window.close()。如果浏览器能够返回历史记录,它将无法进入下一个语句。如果无法返回,它将关闭窗口。

However, please note that if the page has been reached by typing a url, then firefox wont allow the script to close the window.

但是,请注意,如果已通过键入 url 到达该页面,则 Firefox 将不允许脚本关闭窗口。

回答by bobince

You can't directly check whether the back button is usable. You can look at history.length>0, but that will hold true if there are pages aheadof the current page as well. You can only be surethat the back button is unusable when history.length===0.

您无法直接检查后退按钮是否可用。您可以查看history.length>0,但如果当前页面之前还有页面,则这将成立。您只能确定后退按钮在 时不可用history.length===0

If that's not good enough, about all you can do is call history.back()and, if your page is still loaded afterwards, the back button is unavailable! Of course that means if the back button isavailable, you've just navigated away from the page. You aren't allowed to cancel the navigation in onunload, so about all you can do to stop the back actually happening is to return something from onbeforeunload, which will result in a big annoying prompt appearing. It's not worth it.

如果这还不够好,您所能做的就是调用history.back(),如果您的页面之后仍然加载,则后退按钮不可用!当然,如果手段后退按钮可用的,你刚刚从页面导航离开。您不能取消 中的导航onunload,因此您可以做的所有阻止实际发生的返回就是从 返回某些内容onbeforeunload,这将导致出现一个令人讨厌的大提示。这不值得。

In fact it's normally a Really Bad Idea to be doing anything with the history. History navigation is for browser chrome, not web pages. Adding “go back” links typically causes more user confusion than it's worth.

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

回答by Blitzlord

Be careful with window.history.lengthbecause it includes also entries for window.history.forward()

小心,window.history.length因为它也包括条目window.history.forward()

So you may have maybe window.history.lengthwith more than 1 entries, but no history back entries. This means that nothing happens if you fire window.history.back()

因此,您可能有window.history.length超过 1 个条目,但没有历史记录条目。这意味着如果你开火什么都不会发生window.history.back()

回答by Gromo

history.lengthis useless as it does not show if user can go back in history. Also different browsers uses initial values 0 or 1 - it depends on browser.

history.length没有用,因为它没有显示用户是否可以回到历史。不同的浏览器也使用初始值 0 或 1 - 这取决于浏览器。

The working solution is to use $(window).on('beforeunload'event, but I'm not sure that it will work if page is loaded via ajax and uses pushState to change window history.

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

So I've used next solution:

所以我使用了下一个解决方案:

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

回答by Pascal Raszyk

I came up with the following approach. It utilizes the onbeforeunload event to detect whether the browser starts leaving the page or not. If it does not in a certain timespan it'll just redirect to the fallback.

我想出了以下方法。它利用 onbeforeunload 事件来检测浏览器是否开始离开页面。如果它不在某个时间跨度内,它只会重定向到回退。

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

You can call this function using goBack("fallback.example.org").

您可以使用goBack("fallback.example.org").