How to force reloading a page when using browser back button?
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:
- Working with BFCache article on MDN
- WebKit Page Cache II – The unload Event by Brady Eidson
- pageshow event reference on MDN
- Ajax, back button and DOM updates question
- JavaScript - bfcache/pageshow event - event.persisted always set to false? question
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");
John Doeherskij
Updated on January 30, 2022Comments
-
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:
- user is visiting page1.
- while on page1 - he clicks on a link to page2.
- he is redirected to the page2
- now (Important part!) he clicks on the back button in browser because he wants to go back to page1
- he is back on the page1 - and now the page1 is being reloaded and something is alerted like "You are back!"
-
Lelio Faieta over 7 yearsInstead 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 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
tooff
. 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 over 7 yearsAre you using get or post for your Ajax call?
-
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 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 over 7 yearsNot working ;( I have tried
alert('test');
instead oflocation.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 over 7 yearsIt doesn't work. I havetried Firefox and Chrome and it's not working.
-
Anton Stepanenkov over 7 yearsI've edited answer, try new solution. Thing is you need to push state before, or you won't get popstate event.
-
John Doeherskij over 7 yearsYou 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 over 7 yearsPlease, check my updated question, perhaps you and others misunderstood me. It's much more clearer now, what I want to accomplish. Thank you.
-
Dhiraj over 7 yearsYes i did misunderstood, Thanks for updating question in detail.
-
John Doeherskij over 7 yearsnow 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 over 7 yearsCould 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 over 7 yearsHow 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 over 7 yearsAny new idea how to fix the "double load"?
-
Leonid Vasilev over 7 yearsChrome history traversal is somewhat confusing. Please try
pageshow
solution. -
Dhiraj over 7 yearsLooking for it. I am also trying to come up with some solution. I will drop a comment if i get something
-
John Doeherskij over 7 yearsPlease, 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 over 7 yearsWhat do you mean exactly by refresh the page on going back with browser button?
-
John Doeherskij over 7 yearsI 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 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 over 7 yearsI 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 over 6 yearsThis check worked for me. What does the 2 mean exactly?
-
RitchieD over 6 yearsThis does NOT work in IE. developer.microsoft.com/en-us/microsoft-edge/platform/issues/…
-
Dan G over 6 years@RitchieD - As of today, this works well in IE11 on Windows 10. Note: I am not using EDGE.
-
NMathur about 6 yearsThis 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 almost 6 yearsThis worked like a charm. Great find... It's very fast and reliable not like other answers which were slow compared to this. TY
-
Steven over 5 yearsJust not a fan of "just use jQuery" answers, sorry
-
praaveen V R over 5 yearsthis one worked with chrome browser and didn't with firefox
-
David Vielhuber over 5 yearsThis is deprecated (see w3c.github.io/navigation-timing/#obsolete).
-
konyak over 5 yearsI would remove "true" from reload to use the HTTP cache. There's no point of reloading the assets for most cases.
-
Vincent almost 5 yearsThis is not working for me. What does the "0" represent?
-
zeal over 4 yearsBest solution, but here is the version that I used.
Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.Cache.SetMaxAge(TimeSpan.Zero); Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches); Response.Cache.SetNoStore();
-
Timberman over 4 yearsThis does not reload the page when back, which OP requested
-
secondbreakfast over 4 years
window.performance.navigation
is deprecated. To check the navigation type I usedwindow.performance.getEntriesByType("navigation")[0].type === "back_forward"
-
Avatar over 4 yearsWorked for me in latest Chrome 79.0.3945.117.
-
kvothe__ about 4 yearsThis is the most up to date answer
-
gornvix almost 4 yearsThis code needs to be combined with the code in Leonid's answer above.
-
Tasawar Hussain over 3 yearsThis is working fine for me. I tested in latest Chrome, Firefox, IE and Edge. Didn't check on Safari on Mac.
-
Ben in CA over 3 yearsHas 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 over 3 yearsHas 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 over 3 yearsdeveloper.mozilla.org/en-US/docs/Web/API/… indicates it does not work on Safari or iOS yet...
-
Ben in CA over 3 yearsdeveloper.mozilla.org/en-US/docs/Web/API/… indicates it does not work on Safari or iOS yet...
-
Eric McWinNEr over 3 yearsThis looks like a server-side command. Which language is this written in?
-
anandhu almost 3 yearslocation.reload' is deprecated
-
close almost 3 yearsThis is not answering the question "How to force reloading a page when using browser back button?"
-
dgurtner over 2 yearsThat second snippet worked perfectly for what I needed to accomplish. Thanks!
-
run_the_race over 2 years
-
claasz about 2 yearsAt least for Firefox,
no-store
makes the difference -
AGB about 2 yearsIn 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 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