How to force reloading a page when using browser back button?

176,815

Solution 1

You can use pageshow event to handle situation when browser navigates to your page through history traversal:

window.addEventListener( "pageshow", function ( event ) {
  var historyTraversal = event.persisted || 
                         ( typeof window.performance != "undefined" && 
                              window.performance.navigation.type === 2 );
  if ( historyTraversal ) {
    // Handle page restore.
    window.location.reload();
  }
});

Note that HTTP cache may be involved too. You need to set proper cache related HTTP headers on server to cache only those resources that need to be cached. You can also do forced reload to instuct browser to ignore HTTP cache: window.location.reload( true ). But I don't think that it is best solution.

For more information check:

Solution 2

It's been a while since this was posted but I found a more elegant solution if you are not needing to support old browsers.

You can do a check with

performance.navigation.type

Documentation including browser support is here: https://developer.mozilla.org/en-US/docs/Web/API/Performance/navigation

So to see if the page was loaded from history using back you can do

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

The 2 indicates the page was accessed by navigating into the history. Other possibilities are-

0:The page was accessed by following a link, a bookmark, a form submission, or a script, or by typing the URL in the address bar.

1:The page was accessed by clicking the Reload button or via the Location.reload() method.

255: Any other way

These are detailed here: https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigation


Note Performance.navigation.type is now deprecated in favour of PerformanceNavigationTiming.type which returns 'navigate' / 'reload' / 'back_forward' / 'prerender': https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigationTiming/type

Solution 3

Since performance.navigation is now deprecated, you can try this:

var perfEntries = performance.getEntriesByType("navigation");

if (perfEntries[0].type === "back_forward") {
    location.reload(true);
}

Solution 4

Just use jquery :

jQuery( document ).ready(function( $ ) {

   //Use this inside your document ready jQuery 
   $(window).on('popstate', function() {
      location.reload(true);
   });

});

The above will work 100% when back or forward button has been clicked using ajax as well.

if it doesn't, there must be a misconfiguration in a different part of the script.

For example it might not reload if something like one of the example in the previous post is used window.history.pushState('', null, './');

so when you do use history.pushState(); make sure you use it properly.

Suggestion in most cases you will just need:

history.pushState(url, '', url); 

No window.history... and make sure url is defined.

Hope that helps..

Solution 5

An alternative that solved the problem to me is to disable cache for the page. That make the browser to get the page from the server instead of using a cached version:

Response.AppendHeader("Cache-Control","no-cache, no-store, must-revalidate");
Response.AppendHeader("Pragma", "no-cache");
Response.AppendHeader("Expires", "0");
Share:
176,815
John Doeherskij
Author by

John Doeherskij

Updated on January 30, 2022

Comments

  • John Doeherskij
    John Doeherskij over 2 years

    I need to somehow detect that the user has pressed a browsers back button and reload the page with refresh (reloading the content and CSS) using jquery.

    How to detect such action via jquery?

    Because right now some elements are not reloaded if I use the back button in a browser. But if I use links in the website everything is refreshed and showed correctly.

    IMPORTANT!

    Some people have probably misunderstood what I want. I don't want to refresh the current page. I want to refresh the page that is loaded after I press the back button. here is what I mean in a more detailed way:

    1. user is visiting page1.
    2. while on page1 - he clicks on a link to page2.
    3. he is redirected to the page2
    4. now (Important part!) he clicks on the back button in browser because he wants to go back to page1
    5. he is back on the page1 - and now the page1 is being reloaded and something is alerted like "You are back!"
    • Lelio Faieta
      Lelio Faieta over 7 years
      Instead of hacking normal user behavior why don't you try to understand why your code is not working on page load and you need the page to reload?
    • John Doeherskij
      John Doeherskij over 7 years
      @LelioFaieta I change classes to show changes. If user clicks on something the value changes in the database via ajax. When the ajax is done css class cahnge for example from on to off. And it's ok, it's saved in db, users see everything correctly. Now he clicks on some other link. For example about us page, right? Now, he is on the about us page. Be decides to go back to the previous page and clicks the back button in browser. And when he is back, he sees the changes on the page as the browser showed the page (probably some browser cahing) before he triggerd the ajax (on/off classes)
    • Lelio Faieta
      Lelio Faieta over 7 years
      Are you using get or post for your Ajax call?
    • John Doeherskij
      John Doeherskij over 7 years
      @LelioFaieta part2.. I use also data attribute and it has no effect. Everything would be great if the page was reloaded. If I press F5 on that page the values he changed via ajax are shown. I think this is some browser chaching related issue, when the css/html part is not fully reloaded. It reloads only after pressing f5
    • John Doeherskij
      John Doeherskij over 7 years
      @LelioFaieta $.ajax({ url: url, method: 'post', processData: false, contentType: false, cache: false, dataType: 'json', data: formData, }) Do you think that this could be by ajax? it would be great if this was the case.
  • John Doeherskij
    John Doeherskij over 7 years
    Not working ;( I have tried alert('test'); instead of location.reload(true); but still nothing. I have tried firefox and chrome but nothing. I have tried inside document ready, outside , but nothing works. if I try simple alert() or any jquery code tht works. I have a lot of jquery code on my page and it works.
  • John Doeherskij
    John Doeherskij over 7 years
    It doesn't work. I havetried Firefox and Chrome and it's not working.
  • Anton Stepanenkov
    Anton Stepanenkov over 7 years
    I've edited answer, try new solution. Thing is you need to push state before, or you won't get popstate event.
  • John Doeherskij
    John Doeherskij over 7 years
    You have probably misunderstood whan I want. I have updated my question with a more detailed description. Please, check it again if you have time, thank you.
  • John Doeherskij
    John Doeherskij over 7 years
    Please, check my updated question, perhaps you and others misunderstood me. It's much more clearer now, what I want to accomplish. Thank you.
  • Dhiraj
    Dhiraj over 7 years
    Yes i did misunderstood, Thanks for updating question in detail.
  • John Doeherskij
    John Doeherskij over 7 years
    now it works. However it's reloading 2 times and it looks a little weird. First time it reloads. nothing - this is the defaut browser behavior probably. The second time it reloads - via your script - the values are refreshed as it should be, but it looks bad , because it reloads two times. Any idea how to improve it a little, so the reloading looks better or reloads only once? It looks better in Chrome than Firefox, the reloading is faster, but I still see the original back state (for a second or half a second) and the script reload is only after that.
  • John Doeherskij
    John Doeherskij over 7 years
    Could you help the user Dhiraj he is on the right track but it's reloading two times. By the way, I have tried window.addEventListener( "unload", function() {} ); but it's doing nothing, the back button works as before, no change whatsoever ;(
  • John Doeherskij
    John Doeherskij over 7 years
    How to unload BFCache? Could you update your code with more specific info? This line window.addEventListener( "unload", function() {} ); doesn't work. Is it complete?
  • John Doeherskij
    John Doeherskij over 7 years
    Any new idea how to fix the "double load"?
  • Leonid Vasilev
    Leonid Vasilev over 7 years
    Chrome history traversal is somewhat confusing. Please try pageshow solution.
  • Dhiraj
    Dhiraj over 7 years
    Looking for it. I am also trying to come up with some solution. I will drop a comment if i get something
  • John Doeherskij
    John Doeherskij over 7 years
    Please, could you update your code with pageshow example how to refresh the page on going back with browser button? There is not much info on that page you have linked. Thank you.
  • Leonid Vasilev
    Leonid Vasilev over 7 years
    What do you mean exactly by refresh the page on going back with browser button?
  • John Doeherskij
    John Doeherskij over 7 years
    I still see a double load ;( Once the default Firefox (shows the old page; from browser cache perhaps?) and then the script fires again. The script will reload it to the stage that is actual, but I still see the old state for a second or so ;( I have the code inside $(document).ready( function() { /* code here */ });
  • John Doeherskij
    John Doeherskij over 7 years
    What do you mean exactly by refresh the page on going back with browser button? Please, read my updated original question, I have described it in detail in 5. steps.
  • John Doeherskij
    John Doeherskij over 7 years
    I want to refresh the content of the page because if I don';t the things I have changed via ajax previously are not changed for some reason when I use the back button. When I use links it shows OK.
  • RitchieD
    RitchieD over 6 years
    This check worked for me. What does the 2 mean exactly?
  • RitchieD
    RitchieD over 6 years
  • Dan G
    Dan G over 6 years
    @RitchieD - As of today, this works well in IE11 on Windows 10. Note: I am not using EDGE.
  • NMathur
    NMathur about 6 years
    This worked like a charm .. I placed it at top most area .. and the page was reloading without loading any other script.
  • Jithin Raj  P R
    Jithin Raj P R almost 6 years
    This worked like a charm. Great find... It's very fast and reliable not like other answers which were slow compared to this. TY
  • Steven
    Steven over 5 years
    Just not a fan of "just use jQuery" answers, sorry
  • praaveen V R
    praaveen V R over 5 years
    this one worked with chrome browser and didn't with firefox
  • David Vielhuber
    David Vielhuber over 5 years
    This is deprecated (see w3c.github.io/navigation-timing/#obsolete).
  • konyak
    konyak over 5 years
    I would remove "true" from reload to use the HTTP cache. There's no point of reloading the assets for most cases.
  • Vincent
    Vincent almost 5 years
    This is not working for me. What does the "0" represent?
  • zeal
    zeal over 4 years
    Best solution, but here is the version that I used. Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.Cache.SetMaxAge(TimeSpan.Zero); Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCach‌​es); Response.Cache.SetNoStore();
  • Timberman
    Timberman over 4 years
    This does not reload the page when back, which OP requested
  • secondbreakfast
    secondbreakfast over 4 years
    window.performance.navigation is deprecated. To check the navigation type I used window.performance.getEntriesByType("navigation")[0].type === "back_forward"
  • Avatar
    Avatar over 4 years
    Worked for me in latest Chrome 79.0.3945.117.
  • kvothe__
    kvothe__ about 4 years
    This is the most up to date answer
  • gornvix
    gornvix almost 4 years
    This code needs to be combined with the code in Leonid's answer above.
  • Tasawar Hussain
    Tasawar Hussain over 3 years
    This is working fine for me. I tested in latest Chrome, Firefox, IE and Edge. Didn't check on Safari on Mac.
  • Ben in CA
    Ben in CA over 3 years
    Has anyone tested this with iOS? I replaced the older performance.navigation.type method with the performance.getEntriesByType("navigation") method, and all the JS on my page stopped working on iOS.
  • Ben in CA
    Ben in CA over 3 years
    Has anyone tested this with iOS? I replaced the older performance.navigation.type method with the performance.getEntriesByType("navigation") method, and all the JS on my page stopped working on iOS.
  • Ben in CA
    Ben in CA over 3 years
    developer.mozilla.org/en-US/docs/Web/API/… indicates it does not work on Safari or iOS yet...
  • Ben in CA
    Ben in CA over 3 years
    developer.mozilla.org/en-US/docs/Web/API/… indicates it does not work on Safari or iOS yet...
  • Eric McWinNEr
    Eric McWinNEr over 3 years
    This looks like a server-side command. Which language is this written in?
  • anandhu
    anandhu almost 3 years
    location.reload' is deprecated
  • close
    close almost 3 years
    This is not answering the question "How to force reloading a page when using browser back button?"
  • dgurtner
    dgurtner over 2 years
    That second snippet worked perfectly for what I needed to accomplish. Thanks!
  • run_the_race
    run_the_race over 2 years
    Other possible values are reload and navigate: developer.mozilla.org/en-US/docs/Web/API/…
  • claasz
    claasz about 2 years
    At least for Firefox, no-store makes the difference
  • AGB
    AGB about 2 years
    In ASP.NET Core 3.1 you can use attributes on the controller action: [ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)], from stackoverflow.com/questions/36838078/…
  • Les Nightingill
    Les Nightingill almost 2 years
    @BeninCA I have tried it in iOS. It doesn't bork the other js on my page, but it also doesn't force a reload for back button navigation