108

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!"
Arghavan
  • 1,131
  • 1
  • 9
  • 15
John Doeherskij
  • 1,479
  • 3
  • 11
  • 17
  • 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? – Lelio Faieta Mar 27 '17 at 10:59
  • 3
    @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) – John Doeherskij Mar 27 '17 at 11:10
  • 1
    Are you using get or post for your Ajax call? – Lelio Faieta Mar 27 '17 at 11:13
  • 1
    @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 Mar 27 '17 at 11:14
  • @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 Mar 27 '17 at 11:15

11 Answers11

105

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:

Leonid Vasilev
  • 10,092
  • 3
  • 31
  • 44
  • 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 Mar 27 '17 at 10:34
  • 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 Mar 27 '17 at 10:48
  • Chrome history traversal is somewhat confusing. Please try `pageshow` solution. – Leonid Vasilev Mar 27 '17 at 10:53
  • 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. – John Doeherskij Mar 27 '17 at 10:55
  • What do you mean exactly by _refresh the page on going back with browser button_? – Leonid Vasilev Mar 27 '17 at 10:58
  • 1
    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 Mar 27 '17 at 11:01
  • `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 Mar 27 '17 at 11:03
  • 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. – John Doeherskij Mar 27 '17 at 11:05
  • 4
    `window.performance.navigation` is deprecated. To check the navigation type I used `window.performance.getEntriesByType("navigation")[0].type === "back_forward"` – zero01alpha Jan 12 '20 at 23:59
58

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

ChrisV
  • 7,478
  • 3
  • 43
  • 37
Lotok
  • 3,925
  • 1
  • 28
  • 42
25

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..

Francesco
  • 397
  • 4
  • 11
25

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

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

if (perfEntries[0].type === "back_forward") {
    location.reload(true);
}
luthier
  • 2,224
  • 3
  • 28
  • 34
7

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.

Dhiraj
  • 1,302
  • 9
  • 17
  • 2
    It doesn't work. I havetried Firefox and Chrome and it's not working. – John Doeherskij Mar 27 '17 at 10:02
  • Please, check my updated question, perhaps you and others misunderstood me. It's much more clearer now, what I want to accomplish. Thank you. – John Doeherskij Mar 27 '17 at 10:17
  • Yes i did misunderstood, Thanks for updating question in detail. – Dhiraj Mar 27 '17 at 10:18
  • 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 Mar 27 '17 at 10:28
  • Any new idea how to fix the "double load"? – John Doeherskij Mar 27 '17 at 10:48
  • Looking for it. I am also trying to come up with some solution. I will drop a comment if i get something – Dhiraj Mar 27 '17 at 10:54
7

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");
Marlon
  • 1,283
  • 2
  • 15
  • 31
  • Best 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();` – zeal Oct 11 '19 at 20:52
  • This looks like a server-side command. Which language is this written in? – Eric McWinNEr Mar 23 '21 at 10:38
4

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

kvothe__
  • 381
  • 2
  • 9
  • 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 Mar 05 '21 at 17:43
  • https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigationTiming/type#browser_compatibility indicates it does not work on Safari or iOS yet... – Ben in CA Mar 05 '21 at 17:44
2

Reload is easy. You should use:

location.reload(true);

And detecting back is :

window.history.pushState('', null, './');
  $(window).on('popstate', function() {
   location.reload(true);
});
  • 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 Mar 27 '17 at 10:01
  • I've edited answer, try new solution. Thing is you need to push state before, or you won't get popstate event. – Anton Stepanenkov Mar 27 '17 at 10:11
  • 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 Mar 27 '17 at 10:15
0

Use following meta tag in your html header file, This works for me.

<meta http-equiv="Pragma" content="no-cache">
0

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.

Panu Logic
  • 1,495
  • 1
  • 13
  • 20
-1

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

muhammed aslam
  • 44
  • 1
  • 10