Is there any way to close a browser tab with javascript?

Asked

Viewed 18,470 times

3

I have a script that only works locally. Is there any way to close the browser tab using javascript? If so, could they give examples?

3 answers

5

Use the window.close(). It closes the current window/tab.

HTML:

<input type="button" onclick="window.close()" value="Fechar janela" />

<button onclick="window.close()">Fechar janela</button>

<a href="javascript:void()" onclick="window.close()">Fechar janela</a>

Pure Javascript:

document.getElementById("#botaoOuLink").onclick = function()
{
    window.close();
}

With jQuery:

$(elemento).on("click", function() 
{
    window.close();
});

2

I found the same problem and solved using:

window.frames.closewindow();

From the little I studied I saw that javascript can only close windows with window.close(), when you open them by javascript command, then this code posted above accesses the "container" of frames and closes it.

This is because I work with a frame-based system, I did not test with another type of system. Worth a try.

1

Javascript function for closing:

If you want the user to confirm the exit of the page:

function close_window() {
  if (confirm("Fechar Janela?")) {
    close();
  }
}

If not:

function close_window() {
    close();
}

With HTML:

<a href="javascript:close_window();">Fechar Janela</a>

or

<a href="#" onclick="close_window();return false;">Fechar Janela</a>

Original response: Soen

  • The original question asks for confirmation. This question does not.

  • @Dontvotemedown added

  • @Ricardo in this case I close the current, I would have some idea of how to close all but the current?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.