Javascript Close Window Example

This time we’re going to explain how to close a window, regardless of whether it has been opened by a script or not. Take a look!

Closing the script-open window

To close windows we have opened by a script we use the built-in Javascript method window.close(), which is also it’s full syntax, on which we all agree is really easy.

To demonstrate how it works, let’s open a new window and then use the method to close it. The code in the index.html file would go like this:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title>My window</title>

    <script src="windowscript.js"></script>
        <button><a href="javascript: openWindow()">Open New Window</a></button>

        <button><a href="javascript: closeWindow()">Close the  Window</a></button>

Basically, we have created two buttons, one of which, when pressed, executes the openWindow() function, and the other one executes the closeWindow() function.

In the windowscript.js file we would find the code below:

function openWindow()
      myWindow ="",

      myWindow.document.write('<p>New Window</p>');

   function closeWindow()
      if(false == myWindow.closed)
         myWindow.close ();

With the first function openWindow we open a new window with a specific height and width, which contains a paragraph saying New Window.

Closing the current window

You might notice that when we used the method above, we didn’t use it directly as window.close() but through another object. That’s because if we would have done that, we would have closed the current window, regardless of whether we created it with our script or not. However, there might be cases where we want to do exactly that. The code would go like below:

function closeCurrentWindow()

That’s how you can close windows in Javascript.

Download the source code

This was an example of Window Close in Javascript.

Download the source code for this tutorial:

You can download the full source code of this example here : WindowClose

Era Balliu

Era is a Telecommunications Engineering student, with a great passion for new technologies. Up until now she has been coding with HTML/CSS, Bootstrap and other front-end coding languages and frameworks, and her recent love is Angular JS.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button