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);
});
Related
We have an html page with an iframe. As you can see in the code below, iframe is generated by javascript (this is simplified version, since we cannot show the production code). Our goal is to write end-to-end tests using Protractor. We would like to assure the presence of div element inside iframe (the test is also given below). The problem is that the test is passing on Chrome on mac OS Mojave, but falling on Safari 12.0.2.
If iframe is not generated by JS, the test is passed on Safari.
<html>
<head>
<script>
function domOnLoad() {
const rootElement = document.getElementById('root');
const iframeElement = document.createElement('iframe');
iframeElement.frameBorder = 0;
iframeElement.seamless = true;
iframeElement.scrolling = 'no';
rootElement.appendChild(iframeElement);
const divElement = document.createElement('div');
divElement.id = 'iframeRoot';
const textElement = document.createTextNode('Test Iframe');
divElement.appendChild(textElement);
iframeElement.contentDocument.body.appendChild(divElement);
console.log(rootElement);
}
</script>
</head>
<body onload="domOnLoad()">
<div id="root">
</div>
</body>
</html>
describe('Test should have', function() {
browser.waitForAngularEnabled(false);
it('div inside iframe with an id iframeRoot', () => {
browser.get('http://localhost:5000/examples/iframe.html/');
browser.switchTo().frame(0);
var divInsideIframe = $('#iframeRoot');
expect(divInsideIframe.isPresent()).toBeTruthy();
});
});
you have to switch to iframe first
browser.switchTo().frame('iframe');
then try to find element which is in iframe
I hope this will help you
I am trying to make a webpage so that when a link is clicked, it doesn't go to a page, it changes the background color of a sentence in a div, and also changes the sentence. So far it goes to the page, which is fake.
HTML:
<html>
<head>
</head>
<body>
<div id="div1">
Sentence 1
</div>
<div id="div2">
Click to change bgcolor!
</div>
<script type="text/javascript" src="jsdemo.js"></script>
</body>
</html>
JavaScript- jsdemo.js:
function mousedown()
{
document.getElementById('div1').style.backgroundColor="#CCCCCC";
document.div1.innerHTML = "Sentence 2"
}
Get rid of that inline event handler, and use
var div1 = document.getElementById('div1');
document.getElementById('c_link').addEventListener('click', function(e) {
e.preventDefault(); // Avoid following the link
div1.style.backgroundColor = "#CCCCCC";
div1.innerHTML = "Sentence 2";
});
Demo
Try this, and also, why does your <a> tag have a href leading to another page?
<a href="javascript: void(0)"/>
<div>Sample text</div>
<script>
var a = document.getElementsByTagName("a")[0];
var div = document.getElementsByTagName("div")[0];
a.onclick = function() {
div.style.backgroundColor = "#cccccc";
}
</script>
Its better to change onmousedown event to onclick event.
var link = document.getElementById('c_link');
link.onclick = function(e){
e.preventDefault();
var div1 = document.getElementById('div1');
div1.style.backgroundColor = "#CCCCCC";
div1.innerHTML = "Sentence 2";
}
The second sentence doesn't seem to find the div, do this:
function mousedown() {
var container = document.getElementById('div1');
container.style.backgroundColor = "#CCCCCC";
container.innerHTML = "Sentence 2";
}
And change the link to
<div id="div2">
Click to change bgcolor!
</div>
I saw the other response, and I found that this answer is still valid under two assumptions:
You won't need to apply other event handlers to this element and event;
You need compatibility with old browser.
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener#Older_way_to_register_event_listeners
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");
});
})
I am using the following to load an iframe from a bookmarklet:
javascript:(function(d){
var%20modal=document.createElement('iframe');
modal.setAttribute('src','http://myurl.com/page.html?url=
'+encodeURIComponent(window.location.href)+'&
page_title='+document.title);
modal.setAttribute('scrolling','no');
modal.className='modal';
document.body.appendChild(modal);
var c=document.createElement('link');
c.type='text/css';
c.rel='stylesheet';
c.href='//myurl.com/css/wl_iframe.css';
document.body.appendChild(c);
}(document));
and to close it I am trying:
<button onclick="parent.$.iframe.close();">X Close Window</button>
I've also tried:
<button onclick="modal.$.iframe.close();">X Close Window</button>
But they are not working, they do nothing.
I know I can use:
X Close Window
But this then causes a the browser to re-refresh the page they were looking at and also the user has to press the back button twice to get to the page before which is not ideal.
Any ideas?
you should add some name or id to your iframe
javascript:(function(d){
var modal=document.createElement('iframe');
modal.setAttribute('src','http://myurl.com/page.html?url='+encodeURIComponent(window.location.href)+'&page_title='+document.title);
modal.setAttribute('scrolling','no');
modal.setAttribute('name', 'my_modal_window');
modal.className='modal';
document.body.appendChild(modal);
var c=document.createElement('link');
c.type='text/css';
c.rel='stylesheet';
c.href='//myurl.com/css/wl_iframe.css';
document.body.appendChild(c);
}(document));
And then
X close window
EDIT
working solution, have just tested on stackoverflow inside Chrome JS console:
(function(d){
var modal=document.createElement('iframe');
modal.setAttribute('src','http://myurl.com/page.html?url='+encodeURIComponent(window.location.href)+'&page_title='+document.title);
modal.setAttribute('scrolling','no');
modal.setAttribute('name', 'my_modal_window');
modal.className='modal';
document.body.appendChild(modal);
var c=document.createElement('link');
c.type='text/css';
c.rel='stylesheet';
c.href='/css/wl_iframe.css';
document.body.appendChild(c);
var a = document.createElement('a');
a.onclick= function(){
var modals = document.getElementsByName('my_modal_window'),i = modals.length;
while (i--) {
modals[i].parentNode.removeChild(modals[i]);
}
};
a.innerHTML = 'Close Iframes';
document.body.appendChild(a);
}(document))
I forgot to include 'run multiple times in one page' on my last question located here: Create iframe with javascript appending to a div
I need to run the code on multiple div's within the same page. Right now the code below only runs once on the last div. For example if I have 3 div's, all 3 should have an iframe appended to it. Regular javascript. Trying not to use JQuery.
window.onload = function(){
var link = "http://www.somesite.com"
var iframe = document.createElement('iframe');
iframe.frameBorder=0;
iframe.width="300px";
iframe.height="250px";
iframe.id="randomid";
iframe.setAttribute("src", link);
document.getElementById("ad54").appendChild(iframe); //<--this id will be dynamically generated to match div's
}
<div class="ad" id="1"></div>
<div class="ad" id="2"></div>
<div class="ad" id="3"></div>
EDIT: Tested in IE9, Chrome, Safari, Firefox and opera. This code works. No JQuery or loops needed. This code will create the iframe wherever you use it.
var link = "http://www.somesite.com"
document.write(iframe);
var myIframe = parent.document.getElementById("randomid");
myIframe.height = 250;
myIframe.width = 300;
myIframe.src = link;
myIframe.style.border = "0px";
myIframe.style.padding = "0px";
window.onload = function() {
var elements = document.getElementsByTagName('div');
for (var i = 0; i < elements.length; i++) {
append_iframe( elements[i] );
}
}
function append_iframe( div ) {
var link = "http://www.somesite.com"
var iframe = document.createElement('iframe');
iframe.frameBorder=0;
iframe.width="300px";
iframe.height="250px";
iframe.id="randomid";
iframe.setAttribute("src", link);
div.appendChild(iframe);
}
Not a jQuery guy but I think this works
$("div").each(function(d) {
var link = "http://www.somesite.com"
var iframe = document.createElement('iframe');
iframe.frameBorder=0;
iframe.width="300px";
iframe.height="250px";
iframe.id="randomid";
iframe.setAttribute("src", link);
this.appendChild(iframe);
});