Wednesday, April 5, 2023

How to close browser window or tab once click on button / link using jquery and Javascript

Hi, Today I will explain about how to close a browser winow when click on a button or link using Javascript or Jquery, Below piece of snippet work for only CHROME and IE 11 onwards browsers only. The browser does not allow this behavior. Javascript can only close a tab that it opened. Scripts may close only the windows that were opened by it. 

This solution will only work if the window was opened by window.open(...)





<!DOCTYPE html>
<html>
<body>
<a href="#" onclick="close_window();return false;">If you click on this the window will be closed after 1000ms</a>
<script>
function close_window() {
if (confirm("Close Window?")) {
var ww = window.open(window.location, '_self');
ww.close();
//setTimeout(function(){var ww = window.open(window.location, '_self'); ww.close(); }, 1000);
}
}
</script>
</body>
</html>

You return false here to prevent the default behavior for the event. Otherwise the browser will attempt to go to that URL (which it obviously isn't).

You can't close any tab via JavaScript. "This method is only allowed to be called for windows that were opened by a script using the window.open method." In other words, you can only use JavaScript to close a window/tab that was spawned via JavaScript.




Continue Reading →

Popular Posts