Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

137
Vistas
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.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda