I would like to detect when page is refreshed or reloaded in vue.js. I have read the question from this post Do something before reload or close in vue.js. It's using window.onbeforeunload. But the problem for me, where do I put this window function ? Could we use another default method from vuejs for detecting the page that is refreshed ? Thank you
Asked
Active
Viewed 3.0k times
7
-
1for e.g. you could put it in root App component's `created` hook – Jacob Goh May 17 '18 at 01:52
-
How just persisting the data when it's created / changed into something like `localStorage` or `sessionStorage`? Why wait for some kind of "unload" hook? – Phil May 17 '18 at 01:55
-
@JacobGoh Would like to give an example please :-) – Maryadi Poipo May 17 '18 at 02:00
-
@Phil I have edited my question. Its supposed not related to save data – Maryadi Poipo May 17 '18 at 02:01
-
See App.vue in https://codesandbox.io/s/v6ll6mpr6l – Jacob Goh May 17 '18 at 02:13
-
awesome...Thank you @JacobGoh... :-) – Maryadi Poipo May 17 '18 at 02:34
1 Answers
11
You can use the created function to call another function. Example:
created() {
window.addEventListener('beforeunload', this.handler)
},
methods: {
handler: function handler(event) {
// Do Something
}
}
or
created() {
window.addEventListener('beforeunload', function(event) {
event.returnValue = 'Write something'
})
},
Check it : https://forum.vuejs.org/t/detect-browser-close/5001/8

rubotero
- 753
- 1
- 8
- 19
-
3Don't forget to also remove the added event listener on beforeDestroy. Otherwise you might have a lot of unused event listeners slowing down your app. – Stellan Lindell Nov 03 '20 at 11:57
-
1
-
1@KalleshwarKalshetty, where did you get that from? According to MDN, it's very well supported: https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event. – danefondo Jan 19 '22 at 02:06