Search code examples
javascriptback-button

How do I detect that a page is shown from coming back?


Our homepage is an empty page that detects the language of the browser and redirects the visitor automatically to his language page. The back button there (e.g. with Firefox) indeed leads back to our homepage, that unfortunately sends him to his language page again. The visitor seems to be caught on our page, the back button does not work any more.

So how can I detect on our homepage that it is executed by coming back? Then I would let Javascript press the back button again, instead of leading the visitor into the loop again.

The redirect on the homepage is done for every language. The homepage itself has no further content. The redirect is made by window.open:

<script language="javascript" type="text/javascript">
  language = (navigator.userLanguage || navigator.language);
  language = language.substring(0,2); 
  switch (language) {
    case 'fr':
      window.open("fr/index.html",'_self');
      break;
    case 'de':
      window.open("de/index.html",'_self');
      break;
    default:
      window.open("en/index.html",'_self');
      break;
  }
</script>

Solution

  • I used window.sessionStorage to know that the homepage was called the 2nd time (normally coming from the back button of one of the language pages):

    <script language="javascript" type="text/javascript">
      if (window.sessionStorage.getItem("goBack")=="True"){
        window.sessionStorage.setItem("goBack","False"); window.history.back();
      }
      else {
        window.sessionStorage.setItem("goBack","True");
        language = (navigator.userLanguage || navigator.language);
        language = language.substring(0,2);
        switch (language) {
          case 'fr':
            window.open("fr/index.html",'_self');
            break;
          case 'de':
            window.open("de/index.html",'_self');
            break;
          default:
            window.open("en/index.html",'_self');
            break;
        }
      }
    </script>
    

    Thank you all for your comments and answers. You led me to the right way!