How to do button to confirm if you want to quit the page?

Asked

Viewed 898 times

2

How to make my button voltar inform the user if he really wants to leave the page and then direct to the index.html using Javascript? Not quite a button, I’m using href to redirect to index in the meantime. I want to know if it is right to do just that.

<div class="groupb">
   <a href="index.html" class="botoes">voltar</a>
</div>

1 answer

3


Simple, use the event Onbeforeunload or beforeunload it is called before the window is closed. See examples:

Onbeforeunload

function confirmaSaida() {
    return 'Você deseja realmente sair da página?';
}

window.onbeforeunload = confirmaSaida;
<a href="https://answall.com">SOpt</a>

beforeunload

window.addEventListener("beforeunload", function (event) {
  event.returnValue = "Você deseja realmente sair da página?";
});
<a href="https://answall.com">SOpt</a>

Reference

  • 1

    Cool guy! I’m getting until confirmation to exit this page after running your snippet.

  • @DVD I hadn’t noticed that :)

  • Even to turn off the computer rs

Browser other questions tagged

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