Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent safari loading from cache when back button is clicked

Got an issue with safari loading old youtube videos when back button is clicked. I have tried adding onunload="" (mentioned here Preventing cache on back-button in Safari 5) to the body tag but it doesn't work in this case.

Is there any way to prevent safari loading from cache on a certain page?

like image 975
Mark Steggles Avatar asked Jan 09 '12 13:01

Mark Steggles


People also ask

How do I stop safari from caching?

If you don't have the Menu Bar enabled, select the settings gear, then choose “Show Menu Bar“. Select “Develop“ > “Disable Caches“.

Why does the Back button not work on Safari?

Most links that you click on tend to open in the same browser tab. But if the Back button on a page that you just loaded appears grayed out, that's likely because it opened up in a new tab or window. In that case, you can't use the Back button. The only way to go back to the previous page is to switch tabs or windows.

Where does Safari keep cache?

The location of cache files is in your ~/Library/Containers/com. apple. Safari/Data/Library/Caches (earlier versions of macOS: ~/Library/Caches/ ) folder.


2 Answers

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

When page is loaded for bfcache onload event wont be triggered. Instead you can check the persisted property of the onpageshow event. It is set to false on initial page load. When page is loaded from bfcache it is set to true.

Kludgish solution is to force a reload when page is loaded from bfcache.

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

If you are using jQuery then do:

$(window).bind("pageshow", function(event) {     if (event.originalEvent.persisted) {         window.location.reload()      } }); 
like image 159
Mika Tuupola Avatar answered Oct 08 '22 20:10

Mika Tuupola


All of those answer are a bit of the hack. In modern browsers (safari) only on onpageshow solution work,

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

but on slow devices sometimes you will see for a split second previous cached view before it will be reloaded. Proper way to deal with this problem is to set properly Cache-Control on the server response to one bellow

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

like image 36
waj-er-rr Avatar answered Oct 08 '22 20:10

waj-er-rr