Force Page1 to Refresh When Back Button on Page2 is Clicked

Suppose I navigated from Page1.html to Page2.html. How do I force Page1.html to Refresh when I navigate back to it from Page2.html using the back button?

I have seen a post saying to include the following code in the document ready method of my page if I’m using jQuery

            window.history.pushState('', null, './');
              $(window).on('popstate', function() {
              location.reload(true);
            });

I placed the code above in both pages but it didn’t work.

A more reliable way seems to be to use the following:

if(performance.navigation.type == 2){
   location.reload(true);
}

Where 2 says that the page was loaded via history.

Hi Paul, Thanks for your reply. Your solution works great.

1 Like

Hi @liagapi555, the popstate event only gets fired when navigating the same page; instead, you might try reading the state directly (also I’d rather use replaceState() here as pushState() will create a new history entry):

var setState = function (state) {
  window.history.replaceState(
    $.extend({}, window.history.state, state),
    document.title,
    window.location.href
  )
}

if (window.history.state && window.history.state.visited) {
  setState({ visited: false })
  window.location.reload()
} else {
  setState({ visited: true })
}

Hm… actually, the navigation interface is deprecated.

Gah, time to update on something once again.

I’m advised to use PerformanceNavigationTiming instead, which is marked as experimental?

Deprecated from one side, and experimental on the other? Whatever shall i do?

1 Like

Oh I wasn’t aware of that… sometimes I should actually read the pages I’m linking to, especially the content of red boxes LOL! Anyway I guess in this case we’d have to use the deprecated one as a fallback until further notice (or the other way round?). :-/

1 Like

Thank you all for your response. I was beginning to wonder why the solution given by Paul only works the first time but failed after that.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.