online ejemplo bootstrap javascript jquery events iframe

javascript - ejemplo - Detecta cuando un iframe comienza a cargar una nueva URL



iframe src javascript (4)

¿Cómo puedo detectar que un iframe en mi página comience a cargar una página nueva?

Nuestra situación es:

  • Cuando el contenido de iFrame comienza a cambiar, necesitamos mostrar una animación de "carga" y ocultar el cuadro de búsqueda.
  • Sé cómo manejar el evento "iframe ha terminado de cargar" (para ocultar la animación) pero no cómo atrapar el evento inicial de "comenzar a cambiar" ...

Nota: Puedo adjuntar el enlace "clic" de jquery a los enlaces en el menú, que funcionará. Sin embargo, dentro del contenido del iframe hay muchos enlaces de referencias cruzadas, ¡y el evento de "cambio" también se aplica a ellos! Por lo tanto, debemos detectar el evento cuando el usuario haga clic en un enlace dentro del iframe o cuando el iframe src se cambie a través de javascript , ya que también queremos mostrar la carga-animación y ocultar el cuadro de búsqueda.


Cuando está creando dinámicamente el iframe, incluya el evento ONLOAD como ...

F=document.createElement(''iframe''); F.onload=function(){ UpdateDetails( this.contentWindow.document.title, this.contentWindow.location ); }; F.src=''some url''; document.getElementById(''Some_Container'').appendChild(F);

El evento de carga ahora actualizará constantemente las variables globales a continuación a través de la función siguiente, mientras el usuario navega por la red:

var The_Latest_Title=''''; var The_Latest_URL=''''; function UpdateDetails(Title,URL){ The_Latest_Title=Title; The_Latest_URL=URL; }


Encontré una mejor solución si el iframe y la página del contenedor son del mismo origen, no es necesario poner código adicional en la página interna:

<iframe src="same-origin.com" onload="content_finished_loading(this)"></iframe> <script> var indicator = document.querySelector(''.loading-indicator''); var content_start_loading = function() { indicator.style.display = ''block''; }; var content_finished_loading = function(iframe) { indicator.style.display = ''none''; // inject the start loading handler when content finished loading iframe.contentWindow.onunload = content_start_loading; }; </script>


Se me ocurrió la siguiente solución, que solo es posible porque controlamos el contenido del contenido del iframe y la ventana de host.

Dentro del iframe añadimos el siguiente script al pie de página (todas las páginas usan la misma plantilla, por lo que se trata de un cambio en un solo archivo)

<script> window.onunload = function() { // Notify top window of the unload event window.top.postMessage(''iframe_change'', ''*''); }; </script>

Dentro de la ventana de host agregamos este script para monitorear el estado del iframe

function init_content_monitor() { var content = jQuery(''.iframe''); // The user did navigate away from the currently displayed iframe page. Show an animation var content_start_loading = function() { alert (''NOW: show the animation''); } // the iframe is done loading a new page. Hide the animation again var content_finished_loading = function() { alert (''DONE: hide the animation''); } // Listen to messages sent from the content iframe var receiveMessage = function receiveMessage(e){ var url = window.location.href, url_parts = url.split("/"), allowed = url_parts[0] + "//" + url_parts[2]; // Only react to messages from same domain as current document if (e.origin !== allowed) return; // Handle the message switch (e.data) { case ''iframe_change'': content_start_loading(); break; } }; window.addEventListener("message", receiveMessage, false); // This will be triggered when the iframe is completely loaded content.on(''load'', content_finished_loading); }


Ya existe una solución posible en: iFrame src change event detection?

Sin embargo, si desea manipular la página de destino, no es necesario tocar el contenido del archivo de iframe-target. Solo agregue el código JS correcto en la página principal y puede acceder al iframe SAME-ORIGIN. Usé algo como esto:

<iframe id="xyz" ....> ..... <script> var iframeElement = document.getElementById("xyz"); var iframe_El = iframeElement.contentDocument || iframeElement.contentWindow.document; // manipulate iframe_El wih "on complete" events and like that. .... </script>

más en: https://jsfiddle.net/Lnb1stc8/