Search code examples
javascriptjqueryfirefoxsafariback-button

Triggering an onload script (js or jQuery) when loading the page via the browser's "BACK" function


I can't find a way to execute a script when a page is reached via the browser's BACK button or key command. (Background: I need to know if a page was opened using the browser's BACK button or key command. Then I could check for a stored sessionStorage varible and trigger some appropriate stuff).

If, for example, I put this into my page code

<script>
  $(document).ready(function() {
    alert("YES!");
    /* in the real situation: do something */
    })
</script>

, the alert will be displayed when I load the page via a link or by opening it directly by typing its URL into the address bar.

But this alert will not appear when I come to that page via the BACK button.

I tried the same using $(window).on("load", function() {... and $(window).on("navigate", function () {... - no success either...

EDIT / ADDITION:

I just realized that browsers behave differently in this respect: Chrome, Opera, IE and Firefox Windows will reload the page correctly (and trigger document.ready() and onload() events) , but Firefox Mac and Safari will not - they load the whole page from cache without triggering document.ready() or onload(). (I haven't tried mobile browsers yet)

So i searched for solutions avoiding the cached content, but what I've found and tried so far (which is a lot!) hasn't worked either...


Solution

  • after reading lots of posts and trying the solutions in there and narrowing the thing down to a browser issue, I discovered this answer, which forces the page to be reloaded also in Safari (and apparently also Firefox/Mac):

    https://stackoverflow.com/a/13123626/5641669

    Essentially, this jQuery code reloads the page in its original state when coming there via the back button on Safari, which also allows to trigger any desired script on pageload:

    $(window).bind("pageshow", function(event) {
        if (event.originalEvent.persisted) {
            window.location.reload() 
        }
    });