J'ai une chaîne HTML
<html> <body>Hello world</body> </html>
Et je veux le configurer dans un iframe avec JavaScript. J'essaie de définir le HTML comme ceci:
contentWindow.document.body.innerHTML
ou
contentDocument.body.innerHTML
ou
document.body.innerHTML
Mais IE donne "Accès refusé". Ou "Objet ne prend pas en charge cette propriété ou cette méthode". Ou "élément final invalide à l'action". les erreurs.
Voici mon code complet:
<!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>
Vous pourriez utiliser:
document.getElementById('iframe1').contentWindow.document.write("<html><body>Hello world</body></html>");
Voici un jsFiddle , qui fonctionne dans tous les principaux navigateurs.
Notez que, au lieu de contentDocument.write
vous devez utiliser contentWindow.document.write
: cela le rend également contentWindow.document.write
dans IE7.
var htmlString="<body>Hello world</body>"; var myIFrame = document.getElementById('iframe1'); myIFrame.src="javascript:'"+htmlString+"'";
Avec html5, vous pourrez utiliser l' attribut srcdoc .
Le innerHTML
est un peu délicat, en particulier dans IE, où des éléments comme thead
sont en lecture seule et causent beaucoup de problèmes.
Basé sur la documentation sur msdn, vous pouvez essayer documentMode
qui fournit une propriété innerHTML
.
myIFrame = myIFrame.contentWindow || myIFrame.contentDocument.document || myIFrame.contentDocument; myIFrame.document.open(); myIFrame.document.write('Your HTML Code'); myIFrame.document.close();
Cela pourrait seulement fonctionner dans IE.
Que diriez-vous de document.documentElement.innerHTML
. Mais sachez que tout dans la page sera remplacé même par le script qui le fait.
Pour un iframe, ce serait comme ça myIFrame.contentWindow.document.documentElement.innerHTML
Essayez-le:
$('iframe').load(function() { $(this).contents().find('body').append("Hello world"); });
mettre à jour:
$(function(){ $('iframe').load(function() { $(this).contents().find('body').append("Hello world"); }); })