Detecting a page refresh or exit with JavaScript
Published on 2020-04-21 • Modified on 2020-04-21
In this snippet, we will see how to detect a page refresh or exit with JavaScript. On my pomodoro.fun 🍅 side project, there is no persistence of your sessions' logs. If you refresh the page or if you close the tab there you lose all your data. This is the intended behaviour, but it happened to me several times when I confounded my dev and prod browsers! So, I wanted to add an alert to prevent this. It is easy to implement thanks to the following snippet. Refresh or close your browser tab to test ⚙.
/**
* I am using a JavaScript module to isolate the code of each snippet.
* In fact it's a Vue.js mixin. Take the code called by the mounted()
* or the snippetXX() function.
*/
export default {
mounted () {
if (this.isArticle(87)) {
window.addEventListener('beforeunload', function (e) {
e.preventDefault()
e.returnValue = ''
})
}
}
}
More on Stackoverflow Read the doc Random snippet
Call to action
Did you like this post? You can help me back in several ways: (use the "reply" link on the right to comment or to contact me )
- Report any error/typo.
- Report something that could be improved.
- Like and repost!
- Follow me on Bluesky 🦋
- Subscribe to the RSS feed.
- Click on the More on Stackoverflow buttons to make me win "Announcer" badges 🏅.
Thank you for reading! And see you soon on Strangebuzz! 😉
