2009-11-01 10 views
11

Ok, he pasado un tiempo en este problema y esto es lo que he recogido:Internet Explorer llamando window.onbeforeunload en window.open y llamadas AJAX

  1. Si realiza una llamada AJAX en IE7 y tiene una función window.onbeforeunload especificada, llama a la función onbeforeunload.

  2. Si intenta abrir una nueva ventana con window.open SIN molestar a la ventana actual, se llama a onforeforeunload.

¿Alguien sabe cómo detener esto? Incluso intenté establecer una variable en TRUE y verifiqué esa variable en mi función onbeforeunload y aún así funcionó. Solo necesito poder detener la ejecución de ese método para llamadas AJAX y nuevas llamadas a la ventana.

+0

Sólo vio ¡el mismo problema! WTF es IE7 haciendo llamadas. ¡Antes de descargar cuando abres una NUEVA ventana y la actual no cambia! No puedo creerlo ..... –

+0

realmente! pero ¿qué más se puede esperar de IE xD ... y el problema sigue ahí en IE8. – agentfll

+0

Sí, me he topado con esto también. En IE8 – Jon

Respuesta

7

Otra opción y, probablemente, más simple es volver falsa cuando se abre la ventana emergente:

<a onclick="window.open(...); return false;" href="javascript:;" >my link</a> 

Esto parece dejar de decir, de pensar que está dejando la página y que activa el evento. Todas las otras opciones no fueron particularmente viables para mí.

0

¿Intentó eliminar el controlador del evento "onbeforeunload" antes de llamar a window.open? Esto puede ayudar, pero nunca lo probé.

1

Me di cuenta de que solo tiene que desconectar la ventana. Antes de descargar la función antes de hacer cualquier cosa, vuelva a colocarla cuando haya terminado.

Acabo de deshabilitar la característica en IE.

3

OK, he estado teniendo este problema. Tengo un trabajo bastante desordenado para lograrlo.

En mi caso, quiero bloquear la navegación a veces, y no a otros.

Por lo tanto, estoy configurando una bandera en la ventana para decirme si quiero bloquearla. Entonces, donde estás haciendo window.open, justo antes de eso, haz 'window.allowExit = true' y luego en onbeforeunload, busca window.allowExit = true.

que tienen la escritura de Java (ShowHelp) se inició a partir de un enlace:

<a href="javascript:ShowHelp('argument')" >HERE</a> 

onbeforeunload se llama antes de la ShowHelp, por lo que utiliza el onclick para establecer el indicador

<a onclick="window.allowExit = true;" href="javascript:ShowHelp('argument')" >HERE</a> 

Feo como pecado, ¡pero parece funcionar!

2

Esto no es una solución, sino una explicación para cualquiera que esté interesado. Acabo de ejecutar una prueba rápida en IE 7, y se dispara el evento onebeforeunload cada vez que se hace clic en un enlace a menos que el HREF vaya a algún lugar en la misma página, es decir, a menos que contenga un #. Así que supongo que los ingenieros de IE pensaban que cuando alguien hace clic en un enlace que no está en otro lugar de la página, debe abandonar la página, en cuyo caso la página está a punto de descargarse. Huelga decir que hay problemas obvios con este pensamiento.

1

Tuve el mismo problema, en mi caso todas las solicitudes provienen de una llamada ajax, esto simplifica la solución, porque cuando arreglé el problema con el botón estándar hice una función recursiva para redirigir todo onclick a mi función centralizada y luego dispath el derecho clic. Estoy copiando la solución para el problema de href de apoyo a la llamada ajax también. Esta solución evita volver a la página anterior. Poner el código dentro de un archivo llamado BackButton, JS Cualquier comentario de escritura a [email protected] con asunto: javascript BackButton

<!-- backbutton developed by Manuel Parma 2011-06-10 --> 
<!-- email: [email protected] --> 
<!-- Add the next line into the <body> section as a first line --> 
<!-- <script type="text/javascript" src="<path>/backbutton.js"></script> --> 

<!-- Address used when backtoLogin is 1 or when there is not previous page from site --> 
var returningAddress = "http://my returning address" 

<!-- Message to display when an external action (back button, forward button, backspace) move without press the application buttons --> 
var backButtonMessage = "Using the browser's Back button may cause a loss in data. Please use the Back and Continue buttons at the bottom of the form." 

<!-- 0=no/1=yes (assume per default that the back button will be pressed --> 
<!--    and come into action if this was NOT the case)   --> 
var backButtonPressed = 1;  

<!--This var when is setted to 1 avoid to captureEvent set backbuttonPressed to 1, otherwise unload event cannot detect the right state of backButtonPressed--> 
var onbeforeunloadeventFired = 0; 

<!--Indicate to logic back to first page (login) when its value is 1 otherwise the logic back to previous page out of the site--> 
var backtoLogin = 0; 
var DoPostBackWithOptionsHook = null; 
var DoPostBackHook = null; 


<!-- Check the previous status --> 
if (window.name == ""){ 
    <!-- When window.name is empty, this is indicating the first call of site --> 
    window.name = "L0001"; 
} 
else { 
    if (window.name == "L0000_back"){ 
     <!-- In this condition the page is returning after a foward button press --> 
     setBackButton(0); 
     window.name = ""; 

     <!-- the system reload the page to clean the data --> 
     window.location.href = returningAddress; 
    } 
    else { 
     if (window.name.indexOf("_back") > 4){ 
      <!-- when the word back is present, the previous call is sending a message that the back button was pressed and the site is going out --> 

      <!-- get the internal counter --> 
      var sLastValue = modifynamevalue(0);  

      <!-- set the count to go back --> 
      var iCountBack = -(sLastValue * 1); 
      if (backtoLogin == 1) {iCountBack++;}; 

      if (window.history.length - 2 < -iCountBack) { 
       iCountBack = -(window.history.length - 2); 
      } 

      <!-- the site is flag that first page needs to reload --> 
      window.name = "L0000_back";    
      setBackButton(0); 

      <!-- the site is returning to the first page or previous --> 
      window.history.go(iCountBack); 
     } 
     else { 
      <!-- increase the internal counter --> 
      var sLastValue = modifynamevalue(+1); 
      window.name = "L" + sLastValue; 
     } 
    } 
} 

<!-- Set the events needed to manage the back and forwar button situations --> 

$(document).ready(function(){ 
    if (typeof(Sys) == "object") { 
     Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequest); 
     Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequest); 

     window.onbeforeunload = onbeforeunloadEvent; 
     window.onunload = unloadEvent; 
     DoPostBackWithOptionsHook = WebForm_DoPostBackWithOptions; 
     WebForm_DoPostBackWithOptions = WebForm_DoPostBackWithOptionsHook; 

     doPostBackHook = __doPostBack; 
     __doPostBack = __doPostBackHook; 

    } 

    }); 

function WebForm_DoPostBackWithOptionsHook(options) { 
    setBackButton(0); 
    return DoPostBackWithOptionsHook(options) 
} 

function __doPostBackHook(eventTarget, eventArgument) { 
    if (backButtonPressed == 1) { 
     setBackButton(0); 
    } 
    return doPostBackHook(eventTarget, eventArgument) 
} 

function beginRequest(sender, args) { 
    setBackButton(0); 
    <!-- setting onbeforeunloadeventFired = 1 I take care to avoid anyone changed the Backbutton until endrequest --> 
    onbeforeunloadeventFired = 1; 
} 


function endRequest(sender, args) { 
    onbeforeunloadeventFired = 0; 
    setBackButton(1); 
} 

<!-- unload event handler --> 
function unloadEvent(evt) { 
    <!-- double coundition using onbeforeunloadeventFired == 1 garantee avoid problemas with redirect operations --> 
    if ((backButtonPressed == 1) && (onbeforeunloadeventFired == 1)) { 
     <!-- decrement the internal counter --> 
     var sLastValue = modifynamevalue(-1); 
     window.name = "L" + sLastValue + "_back"; 
    } 

    if (DoPostBackWithOptionsHook !== null) { 
     WebForm_DoPostBackWithOptions = DoPostBackWithOptionsHook; 
    }; 

    if (doPostBackHook !== null) { 
     __doPostBack = doPostBackHook; 
    }; 
} 

<!-- on before unload --> 
function onbeforeunloadEvent(evt) { 
    onbeforeunloadeventFired = 1; 
    if (backButtonPressed == 1) { 
     return backButtonMessage; 
    }; 
} 


<!-- used to set right backButtonPressed--> 
function setBackButton(value){ 
    if (value == 0) { 
     backButtonPressed = 0; 
    } 
    else { 
     if (onbeforeunloadeventFired == 0) { 
      backButtonPressed = 1; 
     } 
    } 
} 


<!-- increment and decrment the internal counter stored into windows.name --> 
function modifynamevalue(iIncrement){ 
    var iCount = (window.name.substring(1, 5) * 1) + iIncrement; 

    if (iCount < 0) { 
     iCount = 0; 
    } 

    var sNewValue = iCount.toString(); 

    sNewValue = "0000".substring(0, 4 - sNewValue.length) + sNewValue; 
    return sNewValue; 
} 
0

Esto podría muy posible resolver su problema!

Porque tuve un problema similar y esto fue todo!

window.onbeforeunload = warnFunction; 
var warnRequired = true; 
function warnFunction() { 
    if (warnRequired) return ("Please Stay! Don't go!"); 
    return ; 
} 

Y cada vez que hago una llamada Ajax o popup otra ventana, que acaba de establecer warnRequired a falso.

Otra cosa que debes tener en cuenta al hacer una llamada Ajax es que está sincronizada, ¡de lo contrario, es posible que la variable no se haya establecido todavía! (Un Gotcha desagradable!)

1

Sid_M dijo que un punto válido, con ese diseño de navegador tenemos que diseñar nuestra aplicación en consecuencia.

Por qué ir para etiqueta de anclaje & href de ventanas emergentes, sólo tiene que utilizar el método onclick en la etiqueta o incluso etiqueta td y llamar a window.open

ejemplo simple de una de mi solicitud

<td class="popuplink" onMouseOver="this.style.cursor='hand'" onclick="javascript:openMe('img/howitworks.png', 'pndpopup', 600,650)"><u> How it works</u></td> 
Cuestiones relacionadas