/  Technology   /  Detect browser or tab closing in JavaScript
Detect browser or tab closing in JavaScript

Detect browser or tab closing in JavaScript

 

To detect browser or tab closing in JavaScript we can use the onbeforeunload event. This event occurs when the document is about to be unloaded and it is used when the user accidently clicks on any hyperlink or closes the window, the user gets notified with an alert pop up which confirms if the user agrees to leave the current page.

Such a scenario is possible by using the beforeunload event.

Syntax:

Use the event name in methods like addEventListener (), or set an event handler property.

addEventListener('beforeunload', (event) => { });
onbeforeunload = (event) => { }; 

JavaScript Code:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Detect browser or tab closing in JavaScript</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div>
        <h2>Beforeunload</h2>
        <a href="https://google.com">Spark Radius</a>
        <p id="btn"></p>
    </div>
    <script type="text/javascript"> 
    window.addEventListener('beforeunload', function (e) { 
        e.preventDefault(); 
        e.returnValue = 'Okay Bye'; 
    }); 
</script>
</body>
</html>

In the above code we used the beforeunload event to get user confirmation to leave the current page and navigate to another page when the hyperlink is clicked. 

Output:

Detect browser or tab closing in JavaScript 

 

Leave a comment