Open In App

How to close window using JavaScript which is opened by the user with a URL ?

JavaScript does not allow one to close a window opened by the user, using the window.close() method due to security issues. However, we can close a window by using a workaround. The approach to be followed is by opening the current URL using JavaScript so that it could be closed with a script.

Syntax:



window.close()

Approach: The steps below demonstrate this approach:

Note: This approach may not work on all browsers due to different implementations of browser security.



Example: The example below demonstrates the above steps:




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
 
<body>
 
 <h1 style="color: green;">
    GeeksforGeeks
</h1>
 
<p>
    Click on the button below to
    close the current window.
</p>
 
<!-- Define the button to
       close the window -->
<button onclick="return closeWindow();">
    Close Window
</button>
 
<script type="text/javascript">
    function closeWindow() {
 
        // Open the new window
        // with the URL replacing the
        // current page using the
        // _self value
        let new_window =
            open(location, '_self');
 
        // Close this window
        new_window.close();
 
        return false;
    }
</script>
</body>
 
</html>

Output:


Article Tags :