Prevent Safari/any browser loading from cache when back button is clicked

tn500w_javascript-logo

Prevent Safari/any browser loading from cache when back button is clicked

This problem is caused by back-forward cache. It saves complete state of page when user navigates away. When user navigates back with back button, page is loaded from cache very quickly. This is different from normal cache which only caches HTML code.

This kind of situation arises mainly with IOS devices. You may notice that even if you are using strictest prevention for caching mechanism the pages gets cached, i.e

Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache

Below piece of javascript code is the workaround for this kind of situation.

window.onpageshow = function(event) {
    if (event.persisted) {
        window.location.reload(); 
    }
};

The onpageshow event occurs when a user navigates to a webpage.

The onpageshow event is similar to the onload event, except that it occurs after the onload event when the page first loads. Also, the onpageshow event occurs every time the page is loaded, whereas the onload event does not occur when the page is loaded from the cache.

To find out if a page is loaded directly from the server or if the page is cached, you can use the persisted property of the PageTransitionEvent object. This property returns true if the page is cached by the browser, and false otherwise .

About Anoop Kumar Rai