Using [removed] How to create a 'Go Back' link that takes the user to a link if there's no history for the tab or window?

前端 未结 12 1883
星月不相逢
星月不相逢 2020-12-12 21:36

EDIT-2: None of the answers seem to work. Not even the one I previously marked as the answer of this question. Any help is appreciated. Thanks.

12条回答
  •  忘掉有多难
    2020-12-12 22:15

    The following code did the trick for me.

    html:

    Back

    js:

    home_url = [YOUR BASE URL];
    
    pathArray = document.referrer.split( '/' );
    protocol = pathArray[0];
    host = pathArray[2];
    
    url_before = protocol + '//' + host;
    
    url_now = window.location.protocol + "//" + window.location.host;
    
    
    function goBackOrGoHome(){
      if ( url_before == url_now) {
        window.history.back();    
      }else{
        window.location = home_url;
      };
    }
    

    So, you use document.referrer to set the domain of the page you come from. Then you compare that with your current url using window.location.

    If they are from the same domain, it means you are coming from your own site and you send them window.history.back(). If they are not the same, you are coming from somewhere else and you should redirect home or do whatever you like.

提交回复
热议问题