Reload the site when reached via browsers back button

sorgenkind picture sorgenkind · Jan 28, 2012 · Viewed 57.9k times · Source

Problem: I have a site with dynamic content which needs to be reloaded every time the user sees it. This includes the use case when a user hits the back button on an another site and comes to the site needed to be reloaded. Most (all?) browsers don't refresh the site after this event.

My solution (which isn't quite working): http://www.hunlock.com/blogs/Mastering_The_Back_Button_With_Javascript

window.onbeforeunload = function () {
    // This function does nothing.  It won't spawn a confirmation dialog
    // But it will ensure that the page is not cached by the browser.
}

But it still doesn't refresh the page.

Any ideas what can affect/block the desired behavior? Respectively any other solution suggestions for this problem?

edit:

Set following:

Cache-Control   private, must-revalidate, max-age=0
Expires Sat, 26 Jul 1997 05:00:00 GMT
Pragma  no-cache

and:

<meta name="cache-control" content="no-cache" />
<meta name="expires" content="0" />
<meta name="pragma" content="no-cache" />

still no success.

Answer

Ali Al-Naimi picture Ali Al-Naimi · Oct 5, 2013

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.