1

I want to have some JavaScript code execute when a page loads, but not when the user back-buttons to it. The JavaScript code just displays a message on the page, but I don't want the message displayed when the page is reloaded from the browser's history list.

I am using jQuery, so the code currently looks like this:

$(function() {
    // Code to display the message goes here.
});

Below is a solution I have come up with that seems to work so far, but is there a better way to do this?

Solution so far:

$(function() {
    function isPageFromHistory() {
        if (history.replaceState) {
            return history.state && history.state.loaded;
        } else {
            return location.hash == '#loaded';
        }
    }

    if (!isPageFromHistory()) {
        // Code to display the message goes here.
    }
});

$(window).on('load', function() {
    if (history.replaceState) {
        history.replaceState({ loaded: true }, '');
    } else {
        location.replace('#loaded');
    }
});

The solution marks the page as loaded in the window's onload event handler. For newer browsers, it does this by setting history state using the history.replace() function. For older browsers, it resorts to adding a hash to the URL in the history list.

Of course, this solution has limitations. For newer browsers, you have to be careful not to wipe out the "loaded" value in the history state if you are using history state for other things. For older browsers, you cannot be using URL hashes for other reasons.

John S
  • 21,212
  • 8
  • 46
  • 56
  • possible duplicate: http://stackoverflow.com/questions/829046/how-do-i-detect-if-a-user-has-got-to-a-page-using-the-back-button – pax162 Nov 08 '13 at 19:37
  • @pax162 No, OP wants to detect by cache/history as well. – rgthree Nov 08 '13 at 19:39
  • @pax162 - Thanks for the link. The answer to that question with the highest votes uses a hidden form. I like using history state better, but that might be a better technique for older browsers (instead of using a hash). I will give it a try. – John S Nov 08 '13 at 19:47

0 Answers0