Search code examples
javascriptjqueryhtmldynamichref

Simulate history.go(-1) with Javascript/JQuery


I have three different html files (page1.html, page2.html, page3.html) that each contain a link to the same target in a fourth html file (glossary.html).

For technical reasons, I can't use history.go(-1) or other brower-specific functions, but I can use JavaScript and JavaScript libraries, e.g. JQuery, and LocalStorage.

What would be the best way to mimic the functionality of history.go(-1) with JavaScript?

The technical details are as follows:

page1.html contains the following link:

<a id="page1" href="glossary.html#def1" class="footnote">1</a>

page2.html contains the following link:

<a id="page2" href="glossary.html#def1" class="footnote">1</a>

page3.html contains the following link:

<a id="page3" href="glossary.html#def1" class="footnote">1</a>

glossary.html contains the following link:

<a id="fn1" href="#">↵ Back </a>Term 1: Definition of term one.

I.e., the script(s) should do the following:

  1. Retrieve the id of the calling html page (page1, page2 or page3) and save it as a LocalStorage item or in another suitable persistent manner.

  2. When the user clicks the ↵ Go back link, the href of the definition in glossary.html needs to be updated so that it points to page1.html#page1, page2.html#page2 or page3.html#page3, depending on the html page that the glossary link was clicked on.

What would be the easiest way to solve this problem?


Solution

  • Use localStorage in your glossary.html to record the referer url.

    You can get it easily if you use a server-side script like PHP with $_SERVER['HTTP_REFERER']...
    Then pass it to Javascript by echoing it in a variable.

    urlValue="<? echo $_SERVER['HTTP_REFERER']; ?>";
    localStorage.setItem("referer", urlValue);    // name, value
    

    The rest of the coding adventure is up to you.
    ;)