JavaScript program to close the current tab with OK/Cancel popup

JavaScript program to close the current tab with OK/Cancel popup:

In this post, we will learn how to write a JavaScript program with HTML that asks for the user to close the current tab on clicking a button. It will show one alert with OK and Cancel buttons. If the user clicks on the OK button, the current tab will be closed.

JavaScript program:

Below is the complete JavaScript program:

<!DOCTYPE html>
<html lang="en">

<head>
	<title>Close Tab Example</title>
	<script type="text/javascript">
		function buttonClickListener() {
			var userInput = confirm("Do you want to close this tab ?");

			if(userInput == true){
				close();
			}
		}
	</script>
</head>

<body style="text-align: center;">
	<h1>Click on the button to close this tab</h1>
	<button type="button" id="button" onClick="buttonClickListener()">Click Me</button>
</body>

</html>

Put the code in a html file like index.html, and click to open it in a browser. If you click on the button, it will ask one message with an alert, if you want to close this tab or not. If you click on the OK button, it will close the tab that opens the window.

You might also like: