Detect browser close

Is there any way for VueJS to detect if the user wants to close the tab/browser ?

3 Likes
vew Vue({
  created() {
    document.addEventListener('beforeunload', this.handler)
  },
  methods: {
    handler: function handler(event) {

    }
  }
])

https://developer.mozilla.org/de/docs/Web/Events/beforeunload

Note that this will also fire if the user simply navigates to another website within the same tab/window

4 Likes

Thank you :slight_smile:

vew Vue({
    created() {
        window.addEventListener('beforeunload', this.handler)
},
methods: {
    beforePageDestroyed: function (event) {
        console.log('beforePageDestroyed')
    }
}
])
1 Like

Hello,

I am trying to replicate the same behavior in a beforeunload_codepen, but it is not working !

Please give my a direction to investigate what is not working.

Maybe try replacing document with window

I base in Meteor + Vue.
I use this for auto logout when tab or browse closed.
But it have problem when refresh page, It logout too

// AppLayout.vue
created() {
    window.addEventListener('beforeunload', this.leaving)
  },
  methods: {
    leaving() {
      Meteor.logout()
    },
  },

There is now way around this. A page refresh is basically the same as a new load, to quote MDN: «The window, the document and its resources are about to be unloaded.»

Maybe you can display a prompt, asking the user if s*he wants to log out. But only maybe:

Note: To combat unwanted pop-ups, browsers may not display prompts created in beforeunload event handlers unless the page has been interacted with, or may even not display them at all.

(MDN, again)

Thanks for your reply.

I got this working

created: function () {
    window.addEventListener('beforeunload', function (event) {
      socket.log('leaving', this.$route) // logs to my logger
    }, false)
  },

Solved using arrow functions:

created() {
        window.addEventListener('beforeunload', () => {
            //I CAN ACCESS TO this VARIABLE
            console.log(this.anything);
        }, false)
    },

Using other responses I couldn’t access to this environment

1 Like