'Close current browser tab on button click, using reactjs

Is there a way I can close the current browser tab with a press on the button, using reactjs? I've tried window.close() and self.close() but none of the JavaScript methods seem to work. I don't want the event of close window in React. I want to close the browser tab itself. window.close() can be used only when window.open() is used.



Solution 1:[1]

It's not allowed by the browser to close not self open tab by window.open() so it's kind of work around and convincing the browser it's open by you

by open an empty page in the same page then close it.

You could try that

window.open("about:blank", "_self");
window.close();

Solution 2:[2]

You can close only these tabs which you generated by window.open() for now.

Solution 3:[3]

The final answer is without opening a tab, you can't close it using window.close(). I have searched everywhere, so, I come up with a trick. if you are using reactjs hooks, just open the same url in same tab using useEffect like this-

useEffect(() => {
window.open("https://xyz.abc/", "_self", "");
console.log("open window");
}, []);

Then make function of close and add onclick to close() which has window.close();

This will definitely work! Tried and Tested.

Solution 4:[4]

Yes there is a way and it's not related to React but it is JavaScript. You can create a function to call on button click if you want:

const closeTab = () => {
    window.opener = null;
    window.open("", "_self");
    window.close();
  };
<button onClick={closeTab}>Close Tab</button>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Maksims Kitajevs
Solution 3
Solution 4