简体   繁体   中英

Page history - back button exists?

Is it possible check if there is a value for history.go(-1)? I know you can't access history.previous directly.

I am trying to stay away from document.referrer because I know it can be blocked in some instances.

Here is what I am trying to do. I have an error page, on this page I would like to either have a BACK button (if it's not the only item in history) or a close button (if it is).

if (history.length) {
    //There is history to go back to
    history.go(-1);
}    

Actually, history.length is always one or more, since the current page counts. Also, if you have a forward history (ie you used the back button), those pages also count. So you need a more complicated check:

if( (1 < history.length) && document.referrer ) {

There is no cross-browser approach to accomplish this. Document.Referrer may be set even if no history entry exists.

I came up with the following "hack". 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.

window.goBack = function goBack(fallback){
  var useFallback = true;
  window.onbeforeunload = 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") .

One of the use cases is that you may want to add a back button to any page and also want to make sure that this back button works even if the user goes directly to this page (eg by bookmark, direct link etc).

So either it does perform a history.back() or if there is no entry, it'll redirect to a fallback.

如果历史记录的长度大于0,则它至少包含一个历史记录点。

if (history.length)
 function test() {
        document.URL = document.referrer;            
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM