How to set HTML content into an iframe - javascript

I have a HTML string
<html>
<body>Hello world</body>
</html>
and I want to set it to an iframe with JavaScript. I am trying to set the HTML like this:
contentWindow.document.body.innerHTML
or
contentDocument.body.innerHTML
or
document.body.innerHTML
but IE gives "Access is denied." or "Object does not support this property or method." or "Invalid final element to the action." errors.
Here is my full code:
<!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>

You could use:
document.getElementById('iframe1').contentWindow.document.write("<html><body>Hello world</body></html>");
Here's a jsFiddle, which works in all major browsers.
Note that instead of contentDocument.write you should use contentWindow.document.write: this makes it work in IE7 as well.

var htmlString="<body>Hello world</body>";
var myIFrame = document.getElementById('iframe1');
myIFrame.src="javascript:'"+htmlString+"'";
With html5 you'll be able to use the srcdoc attribute.

The innerHTML is a bit tricky especially in IE, where elements like thead are read-only and cause a lot of trouble.
Based on the documentation on msdn you might try documentMode which provides a innerHTML property.
myIFrame = myIFrame.contentWindow ||
myIFrame.contentDocument.document ||
myIFrame.contentDocument;
myIFrame.document.open();
myIFrame.document.write('Your HTML Code');
myIFrame.document.close();
this might only work in IE.
http://msdn.microsoft.com/en-us/library/ie/ms535862(v=vs.85).aspx
http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
http://msdn.microsoft.com/en-us/library/ie/ms533897(v=vs.85).aspx

How about document.documentElement.innerHTML. But do know that everything in the page will be replaced even the script that does that.
For an iframe it would be like this myIFrame.contentWindow.document.documentElement.innerHTML

I have a problem with 'origin' with the answers here. This is how it's work for me:
const frame1 = document.createElement('iframe');
frame1.name = 'frame1';
//not have to set this style,just for demo
frame1.style.position = 'absolute';
frame1.style.height = '800px';
frame1.style.top = '100px';
frame1.style.left = '100px';
frame1.style.background = 'white';
document.body.appendChild(frame1);
const frameDoc =
frame1.contentWindow || frame1.contentDocument.document ||
frame1.contentDocument;
frameDoc.document.write('<html><head><title></title><body>Hello world</body></html>');
frameDoc.document.close();

In 2023, the correct answer to this problem is to use the srcdoc attribute of the <iframe> element. I can be done straight in your HTML file or with javascript:
document.getElementById('iframe').srcdoc = "<html><body>Hello world!</body></html>";

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

Related

Unable to create a div inside iframe

I have an iframe and I want to add a div to it using JavaScript. But it's not showing up. What am I doing wrong?
<html>
<body>
<iframe
id="zzz"
srcdoc="<html><h1>hello</h1><button>click </button> <button>btn 2</button></html>"
width="500"
height="500">
</iframe>
<script>
let myiframe = document.getElementById("zzz").contentWindow.document;
let mydiv = myiframe.createElement("div");
mydiv.style.background = "red";
mydiv.style.width = "300px";
myiframe.body.appendChild(mydiv);
</script>
</body>
</html>
I'm running this on my local server using VSCode live server extension and I also ran it on w3schools tryit editor too:
See, no red div here!
Edit 1:
Okay, I checked the DOM too. Still nothing here...
Chrome likes a load event - also we can use document.getElementById("zzz").contentDocument;
https://jsfiddle.net/mplungjan/ju8t6xoq/
Stacksnippets will not allow accessing the iFrame
window.addEventListener("load", function() {
let myiframeDocument = document.getElementById("zzz").contentDocument;
let mydiv = myiframeDocument.createElement("div");
mydiv.style.background = "red";
mydiv.style.width = "300px";
mydiv.style.height = "300px";
mydiv.textContent = 'bla'
myiframeDocument.body.appendChild(mydiv);
});

why dont work insertAfter function in javascript

but insertbefore work
var a=document.querySelector("#div");
var y=document.createElement('p');
y.innerText='yazilarucun';
var c=document.querySelector(".p");
a.insertAfter(y,c);
<body>
<div id='div'>yazi
<p class='p'>p etiketi</p>
</div>
</body>
Your Problem Can be fixed pretty easily. You can fix this by adding the node before the node that is after the the node
function insertAfter(newNode, existingNode) {
existingNode.parentNode.insertBefore(newNode, existingNode.nextSibling);
}
//Create Element
var new_para = document.createElement('p');
new_para.innerText = 'yazilarucun';
//Add the element
var old_para = document.querySelector(".p");
insertAfter(new_para, old_para)
<body>
<div id='div'>yazi
<p class='p'>p etiketi</p>
</div>
</body>
The node.insertAfter() is not an inbuilt javascript method, instead we created a user-defined function.
<!DOCTYPE html>
<html>
<body>
<p id="point">Start</p>
<script>
var parentNode = document.getElementsByTagName("body")[0];
var refNode = document.getElementById("point");
function insertAfter(newNode, refNode){
refNode.parentNode.insertBefore(newNode, refNode.nextSibling);
}
var newNode = document.createElement("p");
var textnode = document.createTextNode("End");
newNode.appendChild(textnode);
insertAfter(newNode, refNode);
</script>
</body>
</html>
check : https://www.wikimass.com/js/node-insertafter
There is at least 3 ways to do it.
let targetNode = document.querySelector('#wrapper'),
placeNode = document.querySelector('#footer');
targetNode.after(placeNode);
targetNode.insertAdjacentElement('afterend', placeNode);
targetNode.parentNode.insertBefore(placeNode, targetNode.nextSibling);
The first of these 3, is the newest and simplest. Has been supported since Chrome 54+, Firefox 49+, Edge 17+. No IE support...
Last one is best support, oldest and most complicated one...
Middle one is somewhere in the middle... Is still too hard... Not intuitive enough...

setAttribute iFrame name and Chrome

Here is a simple setAttribute for an iFrame to append a name.
Issue is that the below code works great in all browsers except Chrome.
<iframe id="frame" frameborder="0" src="http://website.ca/"></iframe>
Parent javascript:
(function() {
var newFrameName = "hello";
document.getElementById("frame").setAttribute("name", newFrameName);
})();
in the iFrame:
var iframeName = window.name;
alert (iframeName );
Alert calls "Hello" in all browsers, Chrome calls "frame" -- which is the ID of the iFrame.
looking at source (through the elements inspector), in Chrome, I see the correct name for the iFrame: name="Hello" ... but the alert calls the id.
why would that be? I'm i missing anything?
Creating iframe by createElement fixes the issue:
function createFrame() {
frame= document.createElement("iframe");
frame.setAttribute("src", "https://website.ca/");
frame.setAttribute("name", "Hello");
frame.setAttribute("id", "frame");
frame.frameBorder = 0;
frame.style.width = 100 + "%";
frame.style.height = 2300 + "px";
document.getElementById("iframeHolder").appendChild(frame);
}
createFrame();
<div id="iframeHolder"> </div>
Bit of a hack, but it works for this situation.
6 and a half years later I ran into the same problem.
It seems that Chrome sets the window.name property once and doesn't update it when the enclosing iFrame's name (either property or attribute) is updated.
Setting the window.name directly does work however.
So, changing the OP's example from:
(function() {
var newFrameName = "hello";
document.getElementById("frame").setAttribute("name", newFrameName);
})();
into
(function() {
var newFrameName = "hello";
document.getElementById("frame").name = newFrameName; // keep for other browsers
document.getElementById("frame").contentWindow.name = newFrameName;
})();
works...

Javascript difference between document.write and DOM element.AppendChild(text)

I want to embed and show a flash file. It works fine with document.write but when I tried with AppendChild(text) it doesn't show flash but pure text instead. What DOM method to use instead ?
<html>
<head>
<script>
function addText(text,elementId){
if (document.createTextNode){
var mytextNode=document.createTextNode(text)
document.getElementById(elementId).appendChild(mytextNode)
}
}
</script>
</head>
<body>
<div id="test">
</div>
<script>
addText("<embed height='100' width='100' type='application/x-shockwave-flash' allowscriptaccess='always' wmode='transparent' quality='high' swliveconnect='true' name='test' id='test' src='test.swf'>",'test');
</script>
</body></html>
(function () {
var myEmbed = document.createElement("embed");
myEmbed.type="application/x-shockwave-flash";
myEmbed.height='100';
myEmbed.width='100';
…
document.getElementById("test").appendChild(myEmbed);
}());
At first glance such an approach can often seem unnecessarily noisy and worthless, but it integrates much more sanely with the natural syntax of HTML. If you want to be able to write HTML directly into your document, you might be happier with a framework like jQuery, which allows syntax like:
$("<embed src='…'/>")
However, if you're just doing all this to embed Flash, use swfobject.
Because you are creating a text node, not serialised HTML.
You could change the function to...
function addHTML(html, elementId) {
if (document.createElement) {
var holder = document.createElement('div');
holder.innerHTML = html;
var target = document.getElementById(elementId);
while (holder.hasChildNodes()) {
target.appendChild(holder.firstChild);
}
}
}
jsFiddle.

Javascript createElement() not working in Chrome

Javascript createElement() is not working in Chrome but it works in IE and Firefox fine. Why?
It's working perfectly, use this code:
var catDiv = document.createElement("div");
catDiv.innerHTML = "Test";
document.body.appendChild(catDiv);
Another working example (if you have an element with Id = myTableBody in your HTML)
var appendingTo = document.getElementById("myTableBody");
var tr = document.createElement("tr");
tr.setAttribute("name", "i");
appendingTo.appendChild(tr);
var name = document.createElement("Div" );
will work. And later you can add the attributes like
name.colSpan="2";
document.body.appendChild(name);
Note: don't try to use angular brackets like createElement("<div />").
It will not work in Chrome.
Edit: syntax issue in above code fixed. there should be a dot instead of comma.
Beacause your code is messed up, there's nothing wrong with "createElement":
<html>
<head>
<meta charset = "utf-8">
<title></title>
<script>
window.onload = function () {
for (var i = 0; i < 100; i ++) {
var div = document.createElement ("div");
div.style.border = "1px solid black";
div.style.margin = "20px";
div.style.padding = "10px";
document.body.appendChild (div);
}
}
</script>
<style></style>
</head>
<body></body>
</html>
So I also couldn't get createElement() to work in chrome. After reading Caio's post and testing the code provided I figured out what I was doing wrong.
On w3schools.com the examples they provide always use the tag name in all caps ex. createElement("DIV"), which is the way I was using it and with poor results.
After changing from "DIV" to "div" in my own code it instantly worked.
Thanks Caio.

Categories

Resources