Cómo configurar el contenido HTML en un iframe


Tengo una cadena HTML

<html>
  <body>Hello world</body>
</html> 

Y quiero establecerlo en un iframe con JavaScript. Estoy tratando de establecer el HTML de esta manera:

contentWindow.document.body.innerHTML

O

contentDocument.body.innerHTML

O

document.body.innerHTML

Pero IE da " Acceso denegado. el objeto "or" no admite esta propiedad o método."o" Elemento final inválido de la acción." error.

Aquí está mi código completo:

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="jquery_1.7.0.min.js"/>
    <script type="text/javascript">
      $(document).ready(function(){
        var htmlString = "<html><body>Hello world</body></html>";
        var myIFrame = document.getElementById('iframe1');
        // open needed line commentary
        //myIFrame.contentWindow.document.body.innerHTML = htmlString;
        //myIFrame.contentDocument.body.innerHTML = htmlString;
        //myIFrame.document.body.innerHTML = htmlString;
        //myIFrame.contentWindow.document.documentElement.innerHTML = htmlString;
      });
    </script>
  </head>
  <body>
    <p>This is iframe:
      <br>
      <iframe id="iframe1">
      <p>Your browser does not support iframes.</p>
      </iframe>
  </body>
</html>
Author: Mathijs Flietstra, 2013-05-12

5 answers

Podrías usar:

document.getElementById('iframe1').contentWindow.document.write("<html><body>Hello world</body></html>");

Aquí hay un jsFiddle, que funciona en todos los navegadores principales.

Tenga en cuenta que en lugar de contentDocument.write debe usar contentWindow.document.write: esto hace que funcione en IE7 también.

 45
Author: Mathijs Flietstra,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-03 08:08:39
var htmlString="<body>Hello world</body>";
var myIFrame = document.getElementById('iframe1');
myIFrame.src="javascript:'"+htmlString+"'";

Con html5 podrás usar el atributo srcdoc.

 17
Author: Christophe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-16 05:09:12

El innerHTML es un poco complicado, especialmente en IE, donde elementos como thead son de solo lectura y causan muchos problemas.

Basado en la documentación de msdn puede probar documentMode que proporciona una propiedad innerHTML.

myIFrame = myIFrame.contentWindow ||
    myIFrame.contentDocument.document ||
    myIFrame.contentDocument;
myIFrame.document.open();
myIFrame.document.write('Your HTML Code');
myIFrame.document.close();

Esto solo podría funcionar en IE.

 6
Author: MatthiasLaug,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-02 11:55:28

Qué tal document.documentElement.innerHTML. Pero sepa que todo en la página será reemplazado incluso el script que hace eso.

Para un iframe sería así myIFrame.contentWindow.document.documentElement.innerHTML

 0
Author: user568109,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-12 06:56:26

Pruébalo:

$('iframe').load(function() {
    $(this).contents().find('body').append("Hello world");
}); 

Actualización:

$(function(){
    $('iframe').load(function() {
        $(this).contents().find('body').append("Hello world");
    }); 
})
 -2
Author: Binhvi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-15 06:07:48