John
John

Reputation: 321

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.

Upvotes: 18

Views: 53481

Answers (5)

Anayo Oleru
Anayo Oleru

Reputation: 516

JavaScript can't close a window that it didn't directly open.

The script which opened the window must also be the script that closes the window. A new window isn't capable of closing itself via JavaScript. Here is an example below:

function openNewWindow() {
  window.open('www.ventrane.com');
}

function closeOpenedWindow() {
  window.close();
}

To open the page on a new tab, remove the self from window.open("", "_self");

Upvotes: 1

Rashad Ataf
Rashad Ataf

Reputation: 64

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>

Upvotes: 4

Prabhat kumar
Prabhat kumar

Reputation: 694

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.

Upvotes: -1

mooga
mooga

Reputation: 3307

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();

Upvotes: 14

Maksims Kitajevs
Maksims Kitajevs

Reputation: 225

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

Upvotes: 1

Related Questions