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"> <head> <meta charset="UTF-8"> <title>My window</title> <script src="windowscript.js"></script> </head> <body> <p> <button><a href="javascript: openWindow()">Open New Window</a></button> </p> <p> <button><a href="javascript: closeWindow()">Close the Window</a></button> </p> </body> </html>
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 = window.open("", "mywindow","status=1,width=600,height=600"); 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() { window.close(); }
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