Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

213
Visualizações
Notification when user try to close browser or tab

My script

<script type="text/javascript">
      var hook = true;
      window.onbeforeunload = function() {
        if (hook) {
          return "Do you sure what to leave"
        }
      }
      function unhook() {
        hook=false;
      }
    </script> 

This code blocks user when

  • User try to close browser or tab
  • When user clicked external link
  • When user clicked internal link
  • When user refresh the page

I only want to block user when they try to close browser or tab.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

This is normally used to prevent users lost their drafts from unexpected page leave actions, so normally we will only set this up when user typed something in a input/textarea etc..., and it's predictable user action (cause we can detect if user entered anything or not).

But, you want to block user only when they're trying to close browser or tab, this is not a predictable action, and it cannot always be detectable (such like closing browser).

So, if you want to do so, I think you need to attach listeners to any other acceptable page leave actions (like those you mentioned), and cancel blocking by returning null/false in onbeforeunload.

For example, this accept link redirects:

window.onbeforeunload = () => true;

document
  .querySelectorAll("a")
  .forEach((element) =>
    element.addEventListener(
      "click",
      () => (window.onbeforeunload = null)
    )
  );

I don't know how to detect page reload, maybe by detecting F5 button is pressed or not? but this can't know if user manually click refresh button on browser.

Btw, you should really reconsider that why you would like to do that, cause if it's not for prevent users from lose their drafts, then I think it's not a user-friendly action.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda