Show
What works, what doesn’t, in a nutshellPhoto by Nathan Fertig on Unsplash
It’s interesting how often this question comes up. It can be answered very quickly. As the MDN says,
First: Opening and Closing Windows.Windows are opened with window.open(); — full syntax here Windows are closed with window.close(); — full syntax here This is where the MDN statement comes into play. A simple example should clear this up. Example:I’ve created two pages, Page1.html (the parent window) and Page2.html (the child window.)
The JavaScript functions are to,
Running the exampleRun Page1.html and click “Open child”. A child window opens as separate window as a tab. Child opens as a tabGo back to the parent and click “Close child” and the child window closes. Viola! Now, on the parent, click “Close me”. Nothing happened. Bummer!
According to the MDN it can close itself, under the right conditions. Add the following button and closeMe() function to Page2.html (child.) Additions to childRunning the exampleRun Page1.html and click “Open child”. A child window opens as separate window as a tab, just as before. Now click the “Close me” in the child. It closes. Viola! That window closed itself. Observations below. Conclusion:
So the statement,
Makes more sense now. I hope this simple example has cleared a few thing up. Thanks for reading! Hold on. One last comment.
Try it
SolutionYou will notice I had a variable called “childname”. If we store that on the page, we can use it to get a reference again! Below, in Page1.html, I added a text field (could be a hidden field), removed the closeMe() function since that was an epic fail! and modified the closeChild() function to look and see if the reference was lost. If so, use the window’s name stored on the form. Observe closeChild()Running the Example
Happy coding! Can JavaScript close the browser?As of 2017, there is no way to close a web browser tab or window using JavaScript. Modern security standards do not permit this behavior.
How do you close a screen in JavaScript?Simply call window. close() and it will close the current window.
How do you close a website using JavaScript?To close a window or tab that was opened using JavaScript, call window. close() .
What method is used to close a window in JavaScript?close() The Window. close() method closes the current window, or the window on which it was called. This method can only be called on windows that were opened by a script using the Window.
|