browser window close event in javascript code example

Example 1: window closing event js

window.onbeforeunload = function(){
  alert("You are now leaving, are you sure?")
}

Example 2: 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>