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

5 Likes

Thank you :slight_smile:

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

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)

1 Like

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

If I’m syncing to a backend somewhere, is this a good time to initiate a sync/write?

I realize there are other places where I can sync to the backend that is safer, but wondering what the implications are of syncing here. Will it terminate my async request before the promise returns?