9

This issue -was- solved in older versions of Safari (The Safari Back Button Problem). Although running the latest Safari (9.0.1), none of the solutions listed on the previous answer work anymore. Does anyone have a solution to "refresh/reload" the page when the back button on safari is used?

This -was- a way to detect if the page was accessed using the back-button. Although doesn't work in the version of Safari I'm using.

<body onunload=""> 
Community
  • 1
  • 1
Ilan Kleiman
  • 1,149
  • 5
  • 18
  • 36

1 Answers1

30

Other answers bind things to window.onpageshow, but this is the only version that works for me: once your page is in a final state that you don't want to outlive a redirect, you can just bind the pageshow event and then check for the "persisted" property being true to determine if you should reload it.

window.addEventListener("pageshow", function(evt){
        if(evt.persisted){
        setTimeout(function(){
            window.location.reload();
        },10);
    }
}, false);
Dtipson
  • 1,564
  • 16
  • 21
  • 2
    This is gold. We had problems where a mini cart was not updating in Safari and noticed that Amazon and other large sites trigger a page reload to solve the problem in Safari, something probably like this. – wickywills Aug 29 '19 at 10:17
  • 4
    What might be useful as well is adding `document.body.innerHTML = '';` after the reload call to hide the old content artifacts – smnbbrv Nov 29 '19 at 13:24
  • 2
    Details why this works can be found under the keyword **bfcache** (e.g. via [this blog post](https://web.dev/bfcache/)). You can also hook in some code to tidy up in the prior page, instead of doing a full reload, like [here](https://stackoverflow.com/a/68606072/3991164) to avoid unnecessary load. – flaschbier Jul 31 '21 at 22:21
  • 1
    I use this to reconnect my websocket! +1 – simlmx Aug 09 '21 at 21:24
  • What does `persisted` mean in this case? – leo848 Jan 08 '22 at 23:56
  • https://developer.mozilla.org/en-US/docs/Web/API/PageTransitionEvent/persisted Basically if the state of the page is cached or not. I thiiiiiink if you didn't check, triggering reload from the pageshow event would cause an infinite loop. – Dtipson Mar 16 '22 at 15:01
  • More context: https://developer.mozilla.org/en-US/docs/Web/API/Window/pageshow_event – Dtipson Mar 16 '22 at 15:03