How to make button to confirm if you want to leave the page?

2

How do I make my button voltar tell the user if they really want to exit the page and then direct them to index.html using JavaScript? Not quite a button, I'm using href to redirect to index meanwhile. I want to know if it's right to do this.

<div class="groupb">
   <a href="index.html" class="botoes">voltar</a>
</div>
    
asked by anonymous 02.11.2017 / 06:13

1 answer

3

Simple, use the OnBeforeUnload or beforeunload event it is called before the window is closed. Here are the examples:

OnBeforeUnload

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

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

beforeunload

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

Reference

02.11.2017 / 06:23