[html] HTML Button Close Window

I have an html button that I want to close the current window when clicked. I thought I could just set the onclick feature like I did below. Am I missing something?

<button type="button" onclick="javascript:window.close()">Discard</button>

This question is related to html

The answer is


When in the onclick attribute you do not need to specify that it is Javascript.

<button type="button" 
        onclick="window.open('', '_self', ''); window.close();">Discard</button>

This should do it. In order to close it your page needs to be opened by the script, hence the window.open. Here is an article explaining this in detail:

Click Here

If all else fails, you should also add a message asking the user to manually close the window, as there is no cross-browser solution for this, especially with older browsers such as IE 8.


Closing a window that was opened by the user through JavaScript is considered to be a security risk, thus not all browsers will allow this (which is why all solutions are hacks/workarounds). Browsers that are steadily maintained remove these types of hacks, and solutions that work one day may be broken the next.

This was addressed here by rvighne in a similar question on the subject.


Use the code below. It works every time.

<button onclick="self.close()">Close</button>

It works every time in Chrome and also works on Firefox.


November 2019: onclick="self.close()" still works in Chrome while Edge gives a warning that must be confirmed before it will close.

On the other hand the solution onclick="window.open('', '_self', ''); window.close();" works in both.


JavaScript can only close a window that was opened using JavaScript. Example below:

<script>
function myFunction() {
  var str = "Sample";
  var result = str.link("https://sample.com");
  document.getElementById("demo").innerHTML = result;
}
</script>

I know this thread has been answered, but another solution that may be useful for some, particularly to those with multiple pages where they want to have this button, is to give the input an id and place the code in a JavaScript file. You can then place the code for the button on multiple pages, taking up less space in your code.

For the button:

    <input type="button" id="cancel_edit" value="Cancel"></input>

in the JavaScript file:

    $("#cancel_edit").click(function(){
        window.open('','_parent',''); 
        window.close(); 
    });

This site: http://www.computerhope.com/issues/ch000178.htm answers it with the script below

< input type="button" value="Close this window" onclick="self.close()">