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 🍅 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.returnValue = ''

 More on Stackoverflow   Read the doc  Random snippet

  Work with me!