0

I have been looking for a way to detect a page reload, but can't seem to find a viable solution that works.

I looked at this for reference (http://www.tedpavlic.com/post_detect_refresh_with_javascript.php), but did not work on my end. Is there an effective way to detect this?

My overall goal is to detect a page reload so that I can clear my sessionStorage.

anon
  • 75
  • 8
  • 2
    I may be missing something, but if you're trying to clear sessionStorage after every page load why not just clear the session storage on initial load? then you wouldn't need to detect a page refresh – Aaron McGuire Oct 19 '20 at 20:44
  • https://stackoverflow.com/questions/5004978/check-if-page-gets-reloaded-or-refreshed-in-javascript – andy mccullough Oct 19 '20 at 20:45
  • 1
    Have ever heard of `History PopState`?? Please check this document it might help you out: https://developer.mozilla.org/fr/docs/Web/API/Window/popstate_event – Adnane Ar Oct 19 '20 at 20:49
  • @AaronMcGuire are you referring to something like this https://stackoverflow.com/questions/44279582/how-to-clear-the-sessionstorage-on-browser-refresh-but-this-should-not-clear-o/46837510 ? I tried using $window.location.reload(), but kept getting a referenceError – anon Oct 19 '20 at 21:29

1 Answers1

2

I agree with Aaron McGuire's comment--rather than trying to detect a page load, then clear session storage, it'd be easier to clear session storage on page load. You could insert something quick like this at the top of your code:

window.onload = function() {
    sessionStorage.clear()
}
Hello World
  • 361
  • 1
  • 9
  • I mean he could be talking about popstate events, when the agent press the reload button on the browser it sends an event and that event could cancel the page reload and do something else instead. check: https://developer.mozilla.org/fr/docs/Web/API/Window/popstate_event – Adnane Ar Oct 19 '20 at 21:53
  • @AdnaneAr That's fair--and I hadn't known about popstates. However, documentation says "The `popstate` event will be triggered by doing a browser action such as a click on the back or forward button (or calling history.back() or history.forward() in JavaScript)." So a simple reload (whether with browser button or not) shouldn't call any `popstate` events, right? seeing as we're not navigating through the history. – Hello World Oct 19 '20 at 21:58
  • 1
    @HelloWorld this works perfect! I was able to detect a page load then clear my sessionStorage, but I do agree with why it would be best to clear on initial load. Thanks for the help – anon Oct 19 '20 at 22:07
  • @HelloWorld It's hackable tho, and it could be used to detect reloads! – Adnane Ar Oct 19 '20 at 22:18