I have to dynamically create an Iframe and fill it with content, so I am doing the following:
var ifrm = document.createElement("iframe");
ifrm.id = 'myIframe';
document.getElementById('myIframe').contentWindow.document.write(myIframeContent);
The issue is that the iframe content relies on jquery. Jquery is included in the head of myIframeContent like so:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
However using jquery selectors (e.g. $('#myDiv')) in the iframe results in the variable being undefined. I assume because there is a problem loading jquery, but I'm not sure why. Is it due to how the iframe is being created? Other scripts included in the iframe content are working correctly.
Perhaps you just need to escape the <script><\/script>
SO cannot run this due to security errors
var ifrm = document.createElement("iframe");
ifrm.id = 'myIframe';
const myIframeContent = `<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"><\/script>
<div id="myDiv">Hello</div>
<script>$("#myDiv").html("Hello there")<\/script>`;
document.getElementById("content").appendChild(ifrm);
document.getElementById("myIframe").contentWindow.document.write(myIframeContent);
<div id="content"></div>
Related
I am dynamically creating iframe , which just contains content (no src attribute).
var iframe = document.createElement('iframe');
iframe.contentWindow.document.body.innerHTML= my_page_content;
....
however, JS scripts (<script src="....." inside my_page_content) are not being loaded and I have to re-load scripts.
these methods wont help me to reload frame:
//this one emptyfies the iframe at all
iframeElement.src = iframeElement.src
//this one is not possible, because the `<script>` links are embedded in the content already.
var script = doc.createElement('script'); script.src = "jquery.min.js";
framebody.appendChild(script);
what are the solutions to force the iframe to load the included scripts in its html content? maybe I am attaching the content in a wrong way?
The only way I've solved this was to write the body inside iframe using write() command:
var ifr = iframeElement.contentWindow.document;
ifr.open(); ifr.write("<body>"+ my_page_content +"</body>"); ifr.close();
neither appendChild() nor .innerHTML helped me.
<html>
<body>
<iframe id="src">
</body>
</html>
I want to have the iframe show up in the div element through a Javascript function but I can't seem to figure out what isn't working. Any ideas?
document.getElementById('site').src = http://www.w3schools.com/;
Thanks in advance!
Try
document.getElementById('src').src = 'http://www.w3schools.com/';
a) the url should be provided as string (quoted)
b) the id of your iframe is src not site
Your iframe don't have the id site, so your code won't have any effect.
(Also please note that you didn't close the iframe tag) .
Here's the right code (fiddle) .
<input type="button" onclick="changeIframeSrc('myFrame');" value="changeSrc">
<iframe src="http://www.example.com" id="myFrame"></iframe>
<script>
function changeIframeSrc(id) {
e = document.getElementById(id);
e.src = "http://www.wikipedia.com/";
}
</script>
First, a couple small things:
the id on your iframe appears to be src and not site; and
you need to close the iframe tag.
Assuming that you're just dealing with one iframe and it has an id then by all means:
var myIframe = document.getElementById('src');
// gives you just that one iframe element
You may want to consider document.querySelectorAll though, in case you're working with more than one iframe.
var iframes = document.querySelectorAll('iframe');
See that in action: http://jsbin.com/equzey/2/edit
And important side note: if all you need is access to the iframe element (e.g., to manipulate its source or to apply CSS via the style attribute) then the above should be fine. However, if you need to work with the contents of the iframe, you'll need to get inside its web page context with the contentWindow property:
var iframes = document.querySelectorAll('iframe');
iframes[0].contentWindow;
I'm trying to load a zoom.it script dynamically, but I can't seem to do so without document.write. The problem with document.write is that it replaces everything on my page, which I don't want. What other alternatives are there?
This is document.write in action: http://jsfiddle.net/JyT9B/6/ (notice the element that gets removed).
Also, putting the <script> tag straight into the body works: http://jsfiddle.net/gTcRw/5/, but I need it to be dynamically placed.
I've also tried the methods in Ways to add javascript files dynamically in a page, and How to add and remove js files dynamically, but seem to get the error Cannot set property 'innerHTML' of null, which is probably a zoom.it specific thing. I wouldn't mind knowing why this is the case.
The jsfiddle examples of using the other approaches:
$('body').append
$.getScript
document.createElement as per google analytics
document.createElement in a function
Also tried this in vain: .innerHTML - it gets added to the dom but isn't run.
I think the combination of createElement and appendChild should work, in something like this:
http://jsfiddle.net/kbDny/3/
$(function() {
getScript("http://www.zoom.it/aaa.js");
});
function getScript(src) {
var scr = document.createElement("script");
scr.type = "text/javascript";
scr.src = src;
var head = document.getElementsByTagName("head")[0];
head.appendChild(scr);
}
But there's no reason to not use $.getScript - just pass the url as the first argument, like:
$.getScript(url, function (data, textStatus, jqxhr) {
// Script loaded successfully
});
Ended up using an iframe to contain a html page with an embedded script tag.
The benefit of an iframe is that I can show/remove it at will, without having to worry about cleaning up the current page document when removing the script.
ie,
HTML
<body>
<div id="container">
<a id="show" href="#">show</a>
<a id="close" href="#">close</a>
<div id="placeholder"></div>
</div>
</body>
JavaScript
function appendFrame(elem) {
var iframe = document.createElement("iframe");
iframe.id = "iframe";
iframe.setAttribute("src", "about:blank");
iframe.style.width = "200px";
iframe.style.height = "200px";
$(elem).append(iframe);
}
function loadIFrame() {
appendFrame($("#placeholder"));
var doc = document.getElementById('iframe').contentWindow.document;
doc.open();
doc.write("<html><head><title></title></head><body><script src='http://zoom.it/aaa.js'><\/script><\/body><\/html>");
doc.close();
};
$("#show").click(function() {
loadIFrame();
});
$("#close").click(function() {
$("#iframe").remove();
});
JSFiddle solution here: http://jsfiddle.net/7KRcG/2/
I'm writing a script which requires some stuff to be carried out in an iframe. It's a userscript for a site which I do not own, so because of cross-domain issues, I cannot just set the src of the iframe to a page with my own code. Instead, I am dynamically building the iframe.
To do this, I have
function childScripts(){
//Stuff that must be injected into the iframe.
//Needs jQuery
}
//because I'm lazy:
var iframeWin=$('#my-iframe')[0].contentWindow;
//Load jQuery:
var script = iframeWin.document.createElement("script");
script.type = "text/javascript";
script.src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"
iframeWin.document.head.appendChild(script);
//Inject script
var script = iframeWin.document.createElement("script");
script.type = "text/javascript";
script.textContent="("+childScripts.toString()+")()";
iframeWin.document.body.appendChild(script);
Now, the injected script needs jQuery, but for some reason, jQuery isn't loaded when the injected script runs--even though jQuery is in <head> and the injected script is in <body>.
I've tried other workarounds--making the injected script run onload. I don't like the idea of setting a timeout and checking for the existence of jQuery, I'd prefer a more elegant solution.
I've also tried copying the $ object to iframeWin.$, but of course that doesn't work, since it just backreferences to the parent $ and manipulates the parent document.
It's easier to manipulate iframes using jQuery. Please try:
$('<iframe id="my-iframe"/>').load(function(){
$('#my-iframe').contents().find('body').append('asd').end()
.find('body').append('<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"><\/script>').end()
.find('body').append('<script>$(function() {alert("hello from jquery");console.log("hello from jquery"); })<\/script>');
}).appendTo("body");
Placement:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$('<iframe id="my-iframe"/>').load(function(){.....
</script>
</body>
</html>
Is there anyway to unload a page that has been loaded inside an iframe? I do not want to change the iframe src to a blank page if possible. I am basically looking for something that will do something like this $('#frameID').attr("src",""); except that code does not seem to clear the previously loaded page.
Is there a "unload" function that I can call which will reset the iframe so that it does not have any content loaded inside?
The other solutions use innerHTML, which won't always work in XHTML. They also only clear document.body (anything in the <head> is still present). Here is a solution that uses the DOM:
var frame = document.getElementById("myFrame"),
frameDoc = frame.contentDocument || frame.contentWindow.document;
frameDoc.removeChild(frameDoc.documentElement);
This solution uses innerHTML:
var frame = document.getElementById("myFrame"),
frameDoc = frame.contentDocument || frame.contentWindow.document;
frameDoc.documentElement.innerHTML = "";
If you generate dynamically the content of your iframe, all scripts/variable loaded will leak from one write to another. Thus the solution provided by #Eli of clearing the dom element will not work.
In short:
To clean, wrap your iframe into a div element and replace its dom content.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div id="wrapper">
<iframe id="test"></iframe>
</div>
</body>
</html>
To clean:
var wrapper = document.getElementById('wrapper');
wrapper.innerHTML= "<iframe id='test'></iframe>";
In details: Demo of script leakage
Example of script leakage between two iframe writes (tested with Chrome):
var iframe = document.getElementById('test');
// define variable 'a'
var content = "<html><body><script>var a=555;</script></body></html>";
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(content);
iframe.contentWindow.document.close();
// uncomment this to clean the iframe
//document.getElementById('wrapper').innerHTML= "<iframe id='test'></iframe>";
// write 'a' if defined
var content2 = "<html><body><div id='content'></div><script>document.getElementById('content').innerHTML=typeof a === 'undefined' ? 'undefined' : a;</script></body></html>";
var iframe2 = document.getElementById('test');
iframe2.contentWindow.document.open();
iframe2.contentWindow.document.write(content2);
iframe2.contentWindow.document.close();
If you run this code, you will see the output of the second iframe is 555 although it has been defined in the first iframe.
If you uncomment the middle part it will work as expected.
Related question: Avoiding memory leaks loading content into an iframe
Try this,
$("iframe").contents().find("body").html('');
It only clears innerHTML of your tag inside and not actually unload your iframe so you can reuse your iframe without reloading it and its working in all browsers and quite simple!!
$('#frameID').contentWindow.document.body.innerHTML
= '';
As with any iframe, this only works if you're on the same domain.
var frame = document.getElementById("myframe");
frame.src = "about:blank";
This worked from me and prevented memory leaks too.
In my case I had to destroy the parent too. In that case you have to destroy the parent with some delay to prevent memory leak
Removing and recreating the iframe is the safest solution here.
By removing only the innerHTML of the iframe you don't flush the variables stored, the bound eventListeners etc.
Be careful with this, it might cause a lot of problems (like memory leaks, multiple triggers of the same event etc).
$("#frameId").contents().find("div#SomeDIVinsideFrame").remove(); // removes some div content inside iframe
$("#FrameId").remove(); // removes frame
had same problem to show iframe news on http://www.livepage.info
This worked for me, cleared everything within the iframe tag; body, head, html and all:
$("iframe").contents().empty();
If you had previously loaded content by setting the src property of the iframe, you cannot empty the content as it is a violation of cross site scripting.
You can then just set the src property to '' which will make the browser discard the whole content.
$('iframe').prop('src', '');
First, get the document of the frame:
var frame = $('#frameId').get(0);
var frameDoc = frame.contentDocument || frame.contentWindow.document;
Then, blank it:
frameDoc.getElementsByTagName('body')[0].innerHTML = "";
I think this should work too:
$('body', frameDoc).html("");
Now, you might want to do something with any scripts that might be loaded in the head, but this should get you started.
You can trigger unload event of that iframe like
$('body').trigger('unload');
and then remove the iframe from the parent window and reload a new iframe with new src when needed.
$('#iframe_wrapper').html('');
$('#iframe_wrapper').html('<iframe src="...">');
function getContentFromIframe(iFrameName)
{
var myIFrame = document.getElementById(iFrameName);
var content = myIFrame.contentWindow.document.body.innerHTML;
//Do whatever you need with the content
}
it will definitely work !!!!!!!!!!!!!!!!