Detect browser tab close or refresh with JavaScript
You cannot control when user closes or refreshes a web page in a browser tab, but you can let the user know when the tab is closed or refreshed. In this post we will discuss how to detect when a browser tab is closed or refreshed and show an alert.
Advertisements
We can used onbeforeunload event for this purpose. This event is triggered when a user tries to close, refresh the tab or closing the browser itself.
<script type="text/javascript"> window.onbeforeunload = function () { return 'You have unsaved work, it will be lost if you leave this page.'; } </script>
If you are working with jQuery..
$(window).bind('beforeunload', function(event) { return "You have unsaved work, it will be lost if you leave this page."; });
Curly hair, very fair, please share 🙂
Related
alert before closing window tab javascript, ask before leave tab js, before close tab or window js, confirm before window close javascript, confirm tab close, Confirmation before closing of tab/browser django, confirmation before closing of tab/browser using angular 2, confirmation before closing of tab/browser using javascript, Explain JavaScript text alert, Expressing numbers in expanded form - JavaScript, Form Object from string in JavaScript, Formik for form handling in React.js, How to add form validation for empty input fields with JavaScript?, How to call JavaScript function in an alert box?, how to confirm before window close, How to display JavaScript variable value in alert box?, How to monitor Python files for changes?, How to provide new line in JavaScript alert box?, How to show hyperlinks in JavaScript alert?, How to show image in alert box using JavaScript?, How to split string when the value changes in JavaScript?, javascript before close html, javascript confirm tab close, js ask before close, js before close tab, Methods for tracking database schema changes in MySQL?, run script when closing page javascript confirm, send alert before closing tab, Trigger a button click and generate alert on form submission in JavaScript, warninig message on tab closing, What is an alert box in JavaScript?