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.

5

1 Answer 1

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()
}
Sign up to request clarification or add additional context in comments.

4 Comments

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: developer.mozilla.org/fr/docs/Web/API/Window/popstate_event
@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.
@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
@HelloWorld It's hackable tho, and it could be used to detect reloads!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.