screen_rotation
Copied to Clipboard
<html> <head> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <h3>Vue Js Detect user switches tabs or leaves the page</h3> <div id="app"> <h1>{{ message }}</h1> </div> <script type="module"> const app = new Vue({ el: "#app", data() { return { message: 'Hello, world!' }; }, mounted() { document.addEventListener('visibilitychange', this.handleVisibilityChange); }, beforeDestroy() { document.removeEventListener('visibilitychange', this.handleVisibilityChange); }, methods: { handleVisibilityChange() { if (document.hidden) { // User switched tabs or left the page this.message = 'Goodbye, world!'; } else { // User came back to the page this.message = 'Welcome back!'; } } } }); </script> </body> </html>