You can use the window.close()
method to close the current tab in a browser window using JavaScript. However, it’s important to note that for security reasons, this method can only be called from a script that is running on the same page as the script that opened the window.
// Close the current tab
window.close();
Alternatively, you can use the ‘window.open(”,’_self’).close()’ to close the current tab.
// Close the current tab
window.open('','_self').close();
Also, you can use the ‘window.open(“about:blank”,”_self”); window.close();’
// Close the current tab
window.open("about:blank", "_self");
window.close();
Please note that some browsers will not allow you to close a tab using JavaScript, especially when the tab was not opened using JavaScript, so you may need to provide an alternative way for users to close the tab, such as a button that redirects to a different page.
It’s also important to note that it’s not recommended to use this method because this can be considered as a bad user experience, especially if the user is in the middle of a form submission, or the user is in the middle of something important on the page. It’s recommended to use a confirmation dialog to confirm the user before closing the tab.
Also Read:
- What Is a Web Worker In JavaScript?
- How To Sort an Array of Strings In JavaScript?
- ECMAScript vs JavaScript
- What Is Strict Mode In JavaScript?
- Arrow Functions In JavaScript
- Difference Between Node.js and AngularJS With Example
- Difference Between == And === In JavaScript
- What Is JSON In JavaScript
- How To Go Back To Previous Page In JavaScript?
- How To Detect A Mobile Device With JavaScript?
- How To Convert Input Text To Uppercase While Typing Using JavaScript?
- How To Show A Confirmation Message Before Delete In JavaScript?
- How To Detect Browser or Tab Closing In JavaScript?
- How To Get Hash Value From URL Using JavaScript?
- How To Get The Name, Size, And Type Of A File In JavaScript?
- Run JavaScript From The Command Line