Pregunta

Me gustaría para manipular el código HTML dentro de un iframe usando jQuery.

pensé que sería capaz de hacerlo estableciendo el contexto de la función de jQuery para ser el documento del marco flotante, algo como:

$(function(){ //document ready
    $('some selector', frames['nameOfMyIframe'].document).doStuff()
});

Sin embargo, esto no parece funcionar. Un poco de inspección me muestra que las variables en frames['nameOfMyIframe'] son undefined menos que esperar un tiempo para que el iframe para cargar. Sin embargo, cuando el iframe carga las variables no son accesibles (I get permission denied - errores de tipo).

¿Alguien sabe de un trabajo en torno a esto?

¿Fue útil?

Solución

Creo que lo que está haciendo está sujeta a la política del mismo origen . Esta debe ser la razón por la que está recibiendo permiso tipo negado errores.

Otros consejos

Si el <iframe> es del mismo dominio, los elementos son fácilmente accesibles como

$("#iFrame").contents().find("#someDiv").removeClass("hidden");

referencia

$(document).ready(function(){
    $('#frameID').load(function(){
        $('#frameID').contents().find('body').html('Hey, i`ve changed content of <body>! Yay!!!');
    });
});

Si el iframe src es de otro dominio que aún puede hacerlo. Es necesario leer la página externa en PHP y el eco de tu dominio. De esta manera:

iframe_page.php

<?php
    $URL = "http://external.com"

    $domain = file_get_contents($URL)

    echo $domain
?>

A continuación, algo como esto:

display_page.html

<html>
<head>
  <title>Test</title>
 </head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>

<script>

$(document).ready(function(){   
    cleanit = setInterval ( "cleaning()", 500 );
});

function cleaning(){
    if($('#frametest').contents().find('.selector').html() == "somthing"){
        clearInterval(cleanit);
        $('#selector').contents().find('.Link').html('ideate tech');
    }
}

</script>

<body>
<iframe name="frametest" id="frametest" src="http://yourdomain.com/iframe_page.php" ></iframe>
</body>
</html>

Lo anterior es un ejemplo de cómo editar una página externa a través de un iframe sin el acceso denegado etc ...

Me parece más limpio manera:

var $iframe = $("#iframeID").contents();
$iframe.find('selector');

Uso

iframe.contentWindow.document

en lugar de

iframe.contentDocument

Es necesario adjuntar un evento de controlador onload de un iframe, y ejecutar el js allí, por lo que se asegure el iframe ha terminado de cargarse antes de acceder a ella.

$().ready(function () {
    $("#iframeID").ready(function () { //The function below executes once the iframe has finished loading
        $('some selector', frames['nameOfMyIframe'].document).doStuff();
    });
};

Lo anterior va a resolver el problema 'todavía-no-cargado', pero en cuanto a los permisos, si se carga una página en el iframe que procede de un dominio diferente, usted no será capaz de acceder a él debido a la restricciones de seguridad.

Puede utilizar window.postMessage llamar a una función entre la página y su marco flotante (dominios o no).

Documentación

pagina.html

<!DOCTYPE html>
<html>
<head>
    <title>Page with an iframe</title>
    <meta charset="UTF-8" />
    <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script>
    var Page = {
        id:'page',
        variable:'This is the page.'
    };

    $(window).on('message', function(e) {
        var event = e.originalEvent;
        if(window.console) {
            console.log(event);
        }
        alert(event.origin + '\n' + event.data);
    });
    function iframeReady(iframe) {
        if(iframe.contentWindow.postMessage) {
            iframe.contentWindow.postMessage('Hello ' + Page.id, '*');
        }
    }
    </script>
</head>
<body>
    <h1>Page with an iframe</h1>
    <iframe src="iframe.html" onload="iframeReady(this);"></iframe>
</body>
</html>

Iframe.html

<!DOCTYPE html>
<html>
<head>
    <title>iframe</title>
    <meta charset="UTF-8" />
    <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script>
    var Page = {
        id:'iframe',
        variable:'The iframe.'
    };

    $(window).on('message', function(e) {
        var event = e.originalEvent;
        if(window.console) {
            console.log(event);
        }
        alert(event.origin + '\n' + event.data);
    });
    $(window).on('load', function() {
        if(window.parent.postMessage) {
            window.parent.postMessage('Hello ' + Page.id, '*');
        }
    });
    </script>
</head>
<body>
    <h1>iframe</h1>
    <p>It's the iframe.</p>
</body>
</html>

Yo prefiero usar otra variante para el acceso. De los padres puede tener un acceso a la variable en iframe niño. $ es una variable también y usted puede recibir acceso a su justo reclamo window.iframe_id.$

Por ejemplo, window.view.$('div').hide() - Ocultar todos los divs en el marco flotante con id 'vista'

Sin embargo, no funciona en FF. Para una mejor compatibilidad que debe utilizar

$('#iframe_id')[0].contentWindow.$

¿Has probado el clásico, a la espera de la carga para completar usando la función listo orden interna de jQuery?

$(document).ready(function() {
    $('some selector', frames['nameOfMyIframe'].document).doStuff()
} );

K

creo un código de ejemplo. Ahora se puede entender fácilmente de dominio diferente no puede acceder contenido del iframe .. Lo mismo dominio que podemos acceder al contenido iframe

Te comparto mi código, ejecute este código comprobar la consola. Imprimo src imagen a la consola. Hay cuatro iframe, dos iframe proviene de mismo dominio y otros dos de otro dominio (tercero) Usted puede ver a dos src imagen ( https://www.google.com/logos/doodles/2015/googles-new-logo-5078286822539264.3-hp2x.gif

y

https: // www. google.com/logos/doodles/2015/arbor-day-2015-brazil-5154560611975168-hp2x.gif  )  en la consola y también se puede ver a dos error de permiso ( 2 Error: Permiso denegado acceder a la propiedad 'documento'

... irstChild)}, su contenido: la función (a) {return m.nodeName (un "iframe") a.contentDocument ...

) que viene de la tercera parte de marco flotante.

<body id="page-top" data-spy="scroll" data-target=".navbar-fixed-top">
<p>iframe from same domain</p>
  <iframe frameborder="0" scrolling="no" width="500" height="500"
   src="iframe.html" name="imgbox" class="iView">

</iframe>
<p>iframe from same domain</p>
<iframe frameborder="0" scrolling="no" width="500" height="500"
   src="iframe2.html" name="imgbox" class="iView1">

</iframe>
<p>iframe from different  domain</p>
 <iframe frameborder="0" scrolling="no" width="500" height="500"
   src="https://www.google.com/logos/doodles/2015/googles-new-logo-5078286822539264.3-hp2x.gif" name="imgbox" class="iView2">

</iframe>

<p>iframe from different  domain</p>
 <iframe frameborder="0" scrolling="no" width="500" height="500"
   src="http://d1rmo5dfr7fx8e.cloudfront.net/" name="imgbox" class="iView3">

</iframe>

<script type='text/javascript'>


$(document).ready(function(){
    setTimeout(function(){


        var src = $('.iView').contents().find(".shrinkToFit").attr('src');
    console.log(src);
         }, 2000);


    setTimeout(function(){


        var src = $('.iView1').contents().find(".shrinkToFit").attr('src');
    console.log(src);
         }, 3000);


    setTimeout(function(){


        var src = $('.iView2').contents().find(".shrinkToFit").attr('src');
    console.log(src);
         }, 3000);

         setTimeout(function(){


        var src = $('.iView3').contents().find("img").attr('src');
    console.log(src);
         }, 3000);


    })


</script>
</body>

terminé aquí en busca de obtener el contenido de un iframe sin jQuery, por lo que para una persona que quiere para eso, es precisamente esta:

document.querySelector('iframe[name=iframename]').contentDocument

Esta solución funciona igual que iFrame. He creado un script PHP que puede conseguir todos los contenidos de la otra página web, y lo más importante es que usted puede aplicar fácilmente a su costumbre jQuery para que el contenido externo. Por favor refiérase a la siguiente secuencia de comandos que se pueden obtener todos los contenidos de la otra página web y luego puede aplicar su cusom jQuery / JS también. Este contenido puede ser utilizado en cualquier lugar, dentro de cualquier elemento o cualquier página.

<div id='myframe'>

  <?php 
   /* 
    Use below function to display final HTML inside this div
   */

   //Display Frame
   echo displayFrame(); 
  ?>

</div>

<?php

/* 
  Function to display frame from another domain 
*/

function displayFrame()
{
  $webUrl = 'http://[external-web-domain.com]/';

  //Get HTML from the URL
  $content = file_get_contents($webUrl);

  //Add custom JS to returned HTML content
  $customJS = "
  <script>

      /* Here I am writing a sample jQuery to hide the navigation menu
         You can write your own jQuery for this content
      */
    //Hide Navigation bar
    jQuery(\".navbar.navbar-default\").hide();

  </script>";

  //Append Custom JS with HTML
  $html = $content . $customJS;

  //Return customized HTML
  return $html;
}

Para una mayor robustez:

function getIframeWindow(iframe_object) {
  var doc;

  if (iframe_object.contentWindow) {
    return iframe_object.contentWindow;
  }

  if (iframe_object.window) {
    return iframe_object.window;
  } 

  if (!doc && iframe_object.contentDocument) {
    doc = iframe_object.contentDocument;
  } 

  if (!doc && iframe_object.document) {
    doc = iframe_object.document;
  }

  if (doc && doc.defaultView) {
   return doc.defaultView;
  }

  if (doc && doc.parentWindow) {
    return doc.parentWindow;
  }

  return undefined;
}

y

...
var frame_win = getIframeWindow( frames['nameOfMyIframe'] );

if (frame_win) {
  $(frame_win.contentDocument || frame_win.document).find('some selector').doStuff();
  ...
}
...
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top