| by Arround The Web | No comments

How to Detect Browser or Tab Closing in JavaScript?

JavaScript can fulfill the users/developers’ needs through a bundle of events and methods.
It generates a pop-up/alert message for confirmation of the closing of a tab or browser. JavaScript functionality can be extended to detect some events in the browser or in the tab. For instance, it can be used to detect a tab or browser closing by utilizing JavaScript. For this purpose, the beforeunload event of JavaScript is used.

The beforeunload event is suitable for transactions or paying bills, or during the filling of any online form where data loss may occur. This post guides you to apply the beforeunload event to check a tab or browser closing in JavaScript.

How to Detect a Tab or Browser Closing in JavaScript?

An event beforeunload is triggered to detect the closing of the tab or browser. It generates a pop-up or alert message according to the user’s needs. This event is also triggered while refreshing the webpage. Using this event, users prevent the loss of their unsaved data when they mistakenly navigate away from the current tab.

Example

An example is provided by employing the beforeunload event in JavaScript. The event is just triggered before the page closes the tab or web browser.

Code

<html>
<head>
<h2> An example of detect browser or tab closing using JavaScript</h2>
</head>                    
<body>  
<p>A "beforeunload event" is utilized to detect browser or tab closing.</p>                    
<form><input placeholder = "Please write something...."/></form>                              
<script type="text/javascript">
window.addEventListener('beforeunload', function (e) {
e.preventDefault();
e.returnValue = '';
});
</script>
</body>
</html>

 
The description of the code is as follows:

    • An input field is added to interact with the user by writing something.
    • The beforeunload event is employed to check the tab closing event or browser in JavaScript.
    • An addEventListener() is employed to cancel the event of closing the tab or web browser.


Note: Some browsers do not support the beforeunload event without first writing some information in the text field.


The above display demonstrates how the beforeunload event detects the browser or tab closing in JavaScript. Moreover, this event also detects the page reload as well.

Conclusion

The beforeunload event of JavaScript can be used to detect a browser or tab closing. This event creates a pop-up/alert whenever the tab or browser is being closed/refreshed. This article explains the usage and working of the beforeunload event to detect the closing of the tab or browser. The latest web browsers support the beforeunload event to detect the closing of a particular tab or browser. Most of the usage of the beforeunload event is in educational, e-commerce sites, payment methods to prevent the data loss.

Share Button

Source: linuxhint.com

Leave a Reply