How to force reloading a page when using browser back button?
JavascriptJqueryBrowserBrowser CachePage RefreshJavascript Problem Overview
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!"
Javascript Solutions
Solution 1 - Javascript
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 - Javascript
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 - Javascript
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 - Javascript
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 - Javascript
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");
Solution 6 - Javascript
Currently this is the most up to date way reload page if the user clicks the back button.
const [entry] = performance.getEntriesByType("navigation");
// Show it in a nice table in the developer console
console.table(entry.toJSON());
if (entry["type"] === "back_forward")
location.reload();
See here for source
Solution 7 - Javascript
You should use a hidden input as a refresh indicator, with a value of "no":
<input type="hidden" id="refresh" value="no">
Now using jQuery, you can check its value:
$(document).ready(function(e) {
var $input = $('#refresh');
$input.val() == 'yes' ? location.reload(true) : $input.val('yes');
});
When you click on the back button, the values in hidden fields retain the same value as when you originally left the page.
So the first time you load the page, the input's value would be "no". When you return to the page, it'll be "yes" and your JavaScript code will trigger a refresh.
Solution 8 - Javascript
I tried all the solutions from the previous answers. No one worked.
Finally I found this solution, which did worked:
(function () {
window.onpageshow = function(event) {
if (event.persisted) {
window.location.reload();
}
};
})();
Solution 9 - Javascript
Reload is easy. You should use:
location.reload(true);
And detecting back is :
window.history.pushState('', null, './');
$(window).on('popstate', function() {
location.reload(true);
});
Solution 10 - Javascript
I had the same problem, back-button would update the url shown in location field but page-content did not change.
As pointed out by others it is possible to detect whether a change in document.location is caused by back-button or something else, by catching the 'pageshow' -event.
But my problem was that 'pageshow' did not trigger at all when I clicked the back-button. Only thing that happened was the url in location-field changed (like it should) but page-content did not change. Why?
I found the key to understanding what was causing this from: https://developer.mozilla.org/en-US/docs/Web/API/Window/pageshow_event .
It says 'pageshow' -event is caused among other things by "Navigating to the page from another page in the same window or tab" or by "Returning to the page using the browser's forward or back buttons"
That made me ask: "Am I returning to the page, really?". "What identifies a page?". If my back-button did something else than "returning to the page" then of course 'showpage' would not trigger at all. So was I really "returning to a page"? OR was I perhaps staying on the same "page" all the time? What is a "page"? How is a page identified? By a URL?
Turns out me clicking the back-button did NOT "change the page" I was on. It just changed the HASH (the # + something) that was part of my url. Seems the browser does not consider it a different page when the only thing that changes in the URL is the hash.
So I modified the code that manipulates my urls upon clicking of my buttons. In addition to changing the hash I also added a query parameter for which I gave the same value as the hash, without the '#'. So my new URLs look like:
/someUrl?id=something#something
Every page that my app considers to be a "different page" now has a different value for its query-string parameter 'id'. As far as the browser is concerned they are different "pages". This solved the problem. 'Pageshow' -event started triggering and back-button working.
Solution 11 - Javascript
JS Solution That Works On Most Browsers
None of the many other approaches on this page worked for me, perhaps because the "bfcache" is preventing anything from happening when the user navigates back to the page. However, I found that registering a window.onbeforeunload
handler works for me in most browsers, and I believe it works because it implicitly invalidates the "bfcache". Here's the code:
window.onbeforeunload = function() {
window.location.reload(true);
}
This event may be triggered in other cases than "back" button navigation, but it my case that doesn't matter. I tested this on the following platforms on recent versions of the listed browsers in August 2021:
- Linux: works in Chrome and Firefox.
- Android: works in Chrome, Firefox, and Opera.
- OS X: works in Chrome and Safari.
- iOS: doesn't work in Safari.
In my case I don't really care about mobile. I do care about IE, but don't have access to IE, so I couldn't test it. If someone tries this on IE and can report the result in the comments that would be helpful.
Server Side Response Headers That Fix iOS Safari
I found that iOS Safari also works if I invalidate the browser cache using Cache-Control
response header. I.e. sending
Cache-Control: no-store, must-revalidate
fixes iOS Safari. See this SO answer for how to set the Cache-Control
response header on various platforms.
Solution 12 - Javascript
This works in Nov 21 in latest Firefox and Chrome.
window.addEventListener( "pageshow", function ( event ) {
var perfEntries = performance.getEntriesByType("navigation");
if (perfEntries[0].type === "back_forward") {
location.reload();
}
});
Solution 13 - Javascript
Use following meta tag in your html header file, This works for me.
<meta http-equiv="Pragma" content="no-cache">
Solution 14 - Javascript
In Chrome 96 perfEntries[0].type is 'reload', when you use the back button
Solution 15 - Javascript
I found the best answer and it is working perfectly for me
just use this simple script in your link
<A HREF="javascript:history.go(0)">next page</A>
or the button click event
<INPUT TYPE="button" onClick="history.go(0)" VALUE="next page">
when you use this, you refresh your page first and then go to next page, when you return back it will be having the last refreshed state.
I have used it in a CAS login and gives me what I want. Hope it helps .......
> details found from here