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 1846
星月不相逢
星月不相逢 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:19

    check window.history.length or simply, history.length

    EDIT: some browsers start their history with 0, others with 1. adjust accordingly.

    if it has a value of 1, it means it's the first page in that window/tab - then you can have JS redirect you.

    <script>
        function backAway(){
            //if it was the first page
            if(history.length === 1){
                window.location = "http://www.mysite.com/"
            } else {
                history.back();
            }
        }
    </script>
    
    <a href="#" onClick="backAway()">Back</a>
    
    0 讨论(0)
  • 2020-12-12 22:20

    Added a new answer to display the code formatted:

    The thing is that you were checking for document.referer, because you were in ff it was returning always true, then it was navigating to http://mysite.com. Try the following:

    function backAway(){
        if (document.referrer) {
            //firefox, chrome, etc..
            i = 0;
        } else {
            // under ie
            i = 1;
        }
        if (history.length>i)
        {
            // there are items in history property
            history.back();
        } else {
            window.location = 'http://www.mysite.com/';
        }
        return false;
    }
    
    0 讨论(0)
  • 2020-12-12 22:21

    How about using the history replacement function to add the site into the browsers history?

    Try executing the following as soon as the window loads-

    history.replaceState("example", "title", "http://www.example.com");
    

    This should hopefully make it so even if it is the first page they have accessed, the URL you define in the code will be what they're taken to when they click back.

    0 讨论(0)
  • 2020-12-12 22:22

    You need to check both document.referrer and history.length like in my answer to similar question here: https://stackoverflow.com/a/36645802/1145274

    0 讨论(0)
  • 2020-12-12 22:24

    this seems to do the trick:

    function goBackOrGoToUrl() {    
    
        window.history.back();
        window.location = "http://example.com";
    
    }
    

    Call history.back() and then change the location. 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 go to the location specified.

    0 讨论(0)
  • 2020-12-12 22:32

    simply use cookies to store your visited page list.

    and apply some if else.

    EDIT: also use ServerVariables HTTP_REFERER.

    0 讨论(0)
提交回复
热议问题