javascripthtmlhtml5-history

How to prevent history.back() to return back to external website?


So I am trying to make a back button using onclick="history.back()". But the thing is when I enter my website using an external link, and press the back button, it takes me back to the previous page which is external. I know that it has been programmed to do so. But is there any way to prevent it from taking users back to the external website?


Solution

  • One way would be to store in the sessionStorage the history.length value that you received when first visiting the page.

    Then you will store the current index in the history.state. Once you reach back the initial index, you'd prevent the history to go back.

    // To be executed on all the pages of your domain
    
    // check if we already saved it
    let min_index = sessionStorage.getItem("minHistoryIndex");
    // otherwise
    if (min_index === null) {
      // store it
      min_index = history.length;
      sessionStorage.setItem("minHistoryIndex", min_index);
    }
    // first time we come to this history status
    if (!history.state ) {
      history.replaceState({ index: history.length }, "");
    }
    
    const button = document.querySelector("button");
    // if we reached the limit saved in sessionStorage
    if (history.state.index === +min_index) {
      button.disabled = true;
      button.title = "Going back once more would take you out of our website";
    }
    else {
      button.onclick = (evt) => history.back();
    }
    

    Live demo - source

    One problem with this is that if your user decides to go to an other origin from your page and then go back to it manually, you could go back to that external domain, but I guess it's such a corner case that it can be accepted in most cases.