2009-11-26 20 views
11

Tengo un sistema en el que quiero verificar con el usuario si está seguro de que quiere abandonar la página una vez que se establece un indicador sucio.Configuración antes de descargar en body element en Chrome e IE usando jQuery

Estoy usando el siguiente código: en FireFox, puedo ver el origen de la página a través de FireBug y la etiqueta tiene correctamente insertado el atributo onbeforeunload.

En Chrome y FireFox, esto no ocurre sin embargo y soy capaz de navegar fuera de la página sin ninguna advertencia en absoluto. La línea jQuery para actualizar la etiqueta del cuerpo definitivamente se está ejecutando, simplemente no la está ejecutando.

if ($("body").attr('onbeforeunload') == null) { 
    if (window.event) { 
     // IE and Chrome use this 
     $("body").attr('onbeforeunload', 'CatchLeavePage(event)'); 
    } 
    else { 
     // Firefox uses this 
     $("body").attr('onbeforeunload', 'return false;CatchLeavePage(event)'); 
    } 
} 

¿Alguna idea de cómo proceder desde aquí?

+0

pude usar $ ("cuerpo") CSS ("margen", "50 px."); y $ ("cuerpo"). Attr ("prueba", "hola"); parece que no puedo configurar el atributo onbeforeunload ahora ... – Graeme

Respuesta

17

no se puede cancelar la descarga de página devolviendo el valor falso. debe devolver la cadena que se mostrará al usuario en un cuadro de mensaje, y él decide si quiere irse o permanecer en la página (seleccionando el botón "Aceptar" o "Cancelar"), por lo que debe escribir el código como esto:

window.onbeforeunload = function() { 
    return "Are you sure you want to leave this page bla bla bla?"; // you can make this dynamic, ofcourse... 
}; 
3
window.onbeforeunload = function() { return 'Are you sure?' }; 
8

probar este

<script type=\"text/javascript\"> 
     var dont_confirm_leave = 0; //set dont_confirm_leave to 1 when you want the user to be able to leave withou confirmation 
     var leave_message = 'You sure you want to leave?' 
     function goodbye(e) 
     { 
      if(dont_confirm_leave!==1) 
      { 
       if(!e) e = window.event; 
       //e.cancelBubble is supported by IE - this will kill the bubbling process. 
       e.cancelBubble = true; 
       e.returnValue = leave_message; 
       //e.stopPropagation works in Firefox. 
       if (e.stopPropagation) 
       { 
        e.stopPropagation(); 
        e.preventDefault(); 
       } 

       //return works for Chrome and Safari 
       return leave_message; 
      } 
     } 
    window.onbeforeunload=goodbye; 
    </script> 
+0

Omg omg! Salvaste mi día. Parece que Krk está equivocado con su suposición: "No se puede abortar la descarga de la página volviendo falso". O él no es * preciso * suficiente. Parece que (con IE ** solo **) si el evento "onbeforeload" devuelve falso, no se muestra nada. Así que el código en el que estoy trabajando devolvió el mensaje falso, y ningún mensaje con IE, pero ** siempre ** un mensaje que muestra "falso", y pidiendo que se vaya. Tu solución funciona para todos los navegadores. ** '(Gracias) ³²' **. –

+0

muy buena solución, muchas gracias – Dorgham

1

Comprobar este código:

var validNavigation = false; 

function wireUpEvents() { 
var dont_confirm_leave = 0; 
var leave_message = "You sure you want to leave ?"; 

function goodbye(e) { 
if (!validNavigation) { 
if (dont_confirm_leave !== 1) { 
if (!e) e = window.event; 
e.cancelBubble = true; 
e.returnValue = leave_message; 
//e.stopPropagation works in Firefox. 
if (e.stopPropagation) { 
e.stopPropagation(); 
e.preventDefault(); 
} 
//return works for Chrome and Safari 
return leave_message; 
} 
} 
} 

window.onbeforeunload = goodbye; 

document.onkeydown = function() { 
switch (event.keyCode || e.which) { 
case 116 : //F5 button 
validNavigation = true; 
case 114 : //F5 button 
validNavigation = true; 
case 82 : //R button 
if (event.ctrlKey) { 
validNavigation = true; 
} 
case 13 : //Press enter 
validNavigation = true; 
} 

} 
// Attach the event click for all links in the page 
$("a").bind("click", function() { 
validNavigation = true; 
}); 

// Attach the event submit for all forms in the page 
$("form").bind("submit", function() { 
validNavigation = true; 
}); 

// Attach the event click for all inputs in the page 
$("input[type=submit]").bind("click", function() { 
validNavigation = true; 
}); 
} 

// Wire up the events as soon as the DOM tree is ready 
$(document).ready(function() { 
wireUpEvents(); 
}); 
0

Estos guiones WOR k genial, pero ¿y si quiero activar una llamada AJAX cuando el usuario confirme que la ventana está cerrada?

He intentado esto, pero se dispara la llamada AJAX tanto si el usuario hace clic en "Sí, cerrar" o "no, estar aquí" (tratado en Firefox 38.x)

function goodbye(e) { 
    if (!validNavigation) { 
     if (dont_confirm_leave !== 1) { 
      if (!e) e = window.event; 
      e.cancelBubble = true; 
      e.returnValue = leave_message; 
      //e.stopPropagation works in Firefox. 
      if (e.stopPropagation) { 
       e.stopPropagation(); 
       e.preventDefault(); 
      } 

      $.ajax({ 
       async: false, 
       url: "/launch-my-script.php" 
      }); 

      //return works for Chrome and Safari 
      return leave_message; 
     } 
    } 
} 
+0

Por favor, identifique el tipo de evento, y esta debería ser una nueva pregunta, ¿no responde? – MarmiK

0

No es bonita, pero hizo el truco.

var warnclose = true; 
var warn = function(e) { 
    var warning = 'Your warning message.'; 
    if (warnclose) { 
     // Disables multiple calls 
     warnclose = false; 

     // In case we still need warn to be called again 
     setTimeout(function(){ 
      warnclose = true; 
     }, 500); 

     return warning; 
    } 
}; 
window.onbeforeunload = warn; 
Cuestiones relacionadas