javascript window on close code example

Example 1: javascript close window

<!DOCTYPE html>
<html>
<body>

<button onclick="openWin()">Open "myWindow"</button>
<button onclick="closeWin()">Close "myWindow"</button>

<script>
var myWindow;

function openWin() {
  myWindow = window.open("", "myWindow", "width=200,height=100");
  myWindow.document.write("<p>This is 'myWindow'</p>");
}

function closeWin() {
  myWindow.close();
}
</script>

</body>
</html>

Example 2: javascript prompt on window close

// custom message prompt is no more supported (only IE does)
window.addEventListener("beforeunload", function(e) {
	if( someBusyFlag )
    {
  		// ask for stay
		e.preventDefault();
      	// Chrome requires this var set
      	e.returnValue = '';
    }
	else
    {
    	// grant quit
      	delete e['returnValue'];
    }
});