How do I clear the content of my IFRAME element, using javascript, without loading a blank page into it?
I can figure out to do this: iframe_element.src = "blank.html", but there must be a better, instant, method.
about:blank
is a "URL" that is blank. It's always clear
You can set the page's source to that, and it will clear.
var iframe = document.getElementById("myiframe");
var html = "";
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(html);
iframe.contentWindow.document.close();
tested in IE, Firefox and Chrome ... it did it :)
Your technique is the most robust. Its the one I use myself. At times content may be delivered over HTTPS and the use of about:blank can cause warning messages to appear to the effect of "do you want to include content from unsecure location" or some such thing.
Something being instant is a matter of perception however if you have a single Blank.html file on your site configured with a long cache expiry the client will only ever fetch the page once (at the most once per-session).
Or you can do this :
var iframe_element = window.frames['iframe_name'];
iframe_element.document.open();
iframe_element.document.close();
I have had difficulties with "about:blank" on pages with many IFrames. It does not seem to be a valid location in every browser (I never found out for sure, though). Anyway, I am happy with javascript:void(0);
You could also do this:
<html>
<head>
<script>
var doc = null;
window.onload = function() {
alert("Filling IFrame");
doc = document.getElementById("test");
if( doc.document ) {
document.test.document.body.innerHTML = "<h1>test</h1>"; //Chrome, IE
}else {
doc.contentDocument.body.innerHTML = "<h1>test</h1>"; //FireFox
}
setTimeout(function() {
alert("Clearing IFrame");
if( doc.document ) {
document.test.document.body.innerHTML = ""; //Chrome, IE
}else {
doc.contentDocument.body.innerHTML = ""; //FireFox
}
}, 1000);
};
</script>
</head>
<body>
<iframe id="test" name="test">
</iframe>
</body>
</html>
// First I get the window from its Id.
var my_content = document.getElementById('my_iframe').contentWindow.document;
// Then I clear it by setting the body tag inner HTML to an empty string.
my_content.body.innerHTML="";
// Now when I write my new content it does not get appended to the end of the body and the iframe body will contain only fresh content.
my_content.write(new_content);
Just do it:
var iframe = document.getElementById("iframe");
iframe.removeAttribute('srcdoc');
Work in Chrome
Just get the Iframe and remove the documentElement from it. The Iframe will be blank
var frame = document.getElementById("YourFrameId"),
frameDoc = frame.contentDocument || frame.contentWindow.document;
frameDoc.removeChild(frameDoc.documentElement);
function getContentFromIframe(iFrameName)
{
var myIFrame = document.getElementById(iFrameName);
var content = myIFrame.contentWindow.document.body.innerHTML;
//Do whatever you need with the content
}
$("#iframe").contents().find("body").html('');
Related
I just wanted to know,
is it possible to change the source of an iframe without page postback?
if yes, then how.
Using jquery.attr() method, you can change the src parameter.
$("#myifrm").attr("src","your url here");
To see a working sample, take a look at this:
http://jsfiddle.net/YCDtj/
If I am getting your question right, answer is no.
If you will change the source of an iframe, a new page will load in it.
If your markup is
<iframe id='myframe' src='http://www.abc.com' ></iframe>
And you do,
document.getElementById('myframe').src = 'http://www.xyz.com';
it will reload and open xyz.com.
For the first load :
$(document).ready(function() {
var myIframe = document.getElementById('yourIFrameID');
if(myIframe != undefined || myIframe != null)
myIframe.src = "newSource";
});
AND call following setIFrameSrc() function from any place you want to.
function setIFrameSrc(newURL)
{
var myIframe = document.getElementById('yourIFrameID');
if(myIframe != undefined || myIframe != null)
myIframe.src = newURL;
}
This is my code
<script>
var body = "dddddd"
var script = "<script>window.print();</scr'+'ipt>";
var newWin = $("#printf")[0].contentWindow.document;
newWin.open();
newWin.close();
$("body",newWin).append(body+script);
</script>
<iframe id="printf"></iframe>
This works but it prints the parent page, how do I get it to print just the iframe?
I would not expect that to work
try instead
window.frames["printf"].focus();
window.frames["printf"].print();
and use
<iframe id="printf" name="printf"></iframe>
Alternatively try good old
var newWin = window.frames["printf"];
newWin.document.write('<body onload="window.print()">dddd</body>');
newWin.document.close();
if jQuery cannot hack it
Live Demo
document.getElementById("printf").contentWindow.print();
Same origin policy applies.
Easy way (tested on ie7+, firefox, Chrome,safari ) would be this
//id is the id of the iframe
function printFrame(id) {
var frm = document.getElementById(id).contentWindow;
frm.focus();// focus on contentWindow is needed on some ie versions
frm.print();
return false;
}
an alternate option, which may or may not be suitable, but cleaner if it is:
If you always want to just print the iframe from the page, you can have a separate "#media print{}" stylesheet that hides everything besides the iframe. Then you can just print the page normally.
You can use this command:
document.getElementById('iframeid').contentWindow.print();
This command basically is the same as window.print(), but as the window we would like to print is in the iframe, we first need to obtain an instance of that window as a javascript object.
So, in reference to that iframe, we first obtain the iframe by using it's id, and then it's contentWindow returns a window(DOM) object. So, we are able to directly use the window.print() function on this object.
I had issues with all of the above solutions in IE8, have found a decent workaround that is tested in IE 8+9, Chrome, Safari and Firefox. For my situation i needed to print a report that was generated dynamically:
// create content of iframe
var content = '<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">'+
'<head><link href="/css/print.css" media="all" rel="stylesheet" type="text/css"></head>'+
'<body>(rest of body content)'+
'<script type="text/javascript">function printPage() { window.focus(); window.print();return; }</script>'+
'</body></html>';
Note the printPage() javascript method before the body close tag.
Next create the iframe and append it to the parent body so its contentWindow is available:
var newIframe = document.createElement('iframe');
newIframe.width = '0';
newIframe.height = '0';
newIframe.src = 'about:blank';
document.body.appendChild(newIframe);
Next set the content:
newIframe.contentWindow.contents = content;
newIframe.src = 'javascript:window["contents"]';
Here we are setting the dynamic content variable to the iframe's window object then invoking it via the javascript: scheme.
Finally to print; focus the iframe and call the javascript printPage() function within the iframe content:
newIframe.focus();
setTimeout(function() {
newIframe.contentWindow.printPage();
}, 200);
return;
The setTimeout is not necessarily needed, however if you're loading large amounts of content i found Chrome occasionally failed to print without it so this step is recommended. The alternative is to wrap 'newIframe.contentWindow.printPage();' in a try catch and place the setTimeout wrapped version in the catch block.
Hope this helps someone as i spent a lot of time finding a solution that worked well across multiple browsers. Thanks to SpareCycles.
EDIT:
Instead of using setTimeout to call the printPage function use the following:
newIframe.onload = function() {
newIframe.contentWindow.printPage();
}
At this time, there is no need for the script tag inside the iframe. This works for me (tested in Chrome, Firefox, IE11 and node-webkit 0.12):
<script>
window.onload = function() {
var body = 'dddddd';
var newWin = document.getElementById('printf').contentWindow;
newWin.document.write(body);
newWin.document.close(); //important!
newWin.focus(); //IE fix
newWin.print();
}
</script>
<iframe id="printf"></iframe>
Thanks to all answers, save my day.
If you are setting the contents of IFrame using javascript document.write() then you must close the document by newWin.document.close(); otherwise the following code will not work and print will print the contents of whole page instead of only the IFrame contents.
var frm = document.getElementById(id).contentWindow;
frm.focus();// focus on contentWindow is needed on some ie versions
frm.print();
I was stuck trying to implement this in typescript, all of the above would not work. I had to first cast the element in order for typescript to have access to the contentWindow.
let iframe = document.getElementById('frameId') as HTMLIFrameElement;
iframe.contentWindow.print();
Use this code for IE9 and above:
window.frames["printf"].focus();
window.frames["printf"].print();
For IE8:
window.frames[0].focus();
window.frames[0].print();
I am wondering what's your purpose of doing the iframe print.
I met a similar problem a moment ago: use chrome's print preview to generate a PDF file of a iframe.
Finally I solved my problem with a trick:
$('#print').click(function() {
$('#noniframe').hide(); // hide other elements
window.print(); // now, only the iframe left
$('#noniframe').show(); // show other elements again.
});
I have an iframe (id: 'chat') with designMode='on' in Chrome.
On Enter keypress event I call the function send(), which takes the iframe contents and writes it to a socket. My problem is that when clearing the iframe, I lose focus.
How to do I set the focus so I can continue to type text in the iframe?
function send(){
var $iframe = $('#chat');
var text = $iframe.contents().text() + "\n";
socket.send(text);
// When this is done, the focus is lost
// If commented, the focus will not be lost
$iframe.contents().find('body').empty();
// My different failed attempts to regain the focus
//$iframe.focus();
//$iframe.contents().focus();
//$iframe.contents().find('body').focus();
//$iframe.contents().find('body').parent().focus();
//$iframe[0].contentWindow.focus();
// I've also tried all the above with timers
//setTimeout( function(){ $('#chat').contents().focus(); }, 100);
}
I've tried many of the solutions on other questions, but none seems to work.
The trick is to first set focus on the body and then create a Range.
var win = iframe.contentWindow;
var range = win.document.createRange();
range.setStart(win.document.body, 0);
range.setEnd(win.document.body, 0);
win.document.body.focus();
win.getSelection().addRange(range);
This question has been answered here
Basically, if you are not refreshing the iframe you could use:
$iframe[0].contentWindow.focus();
Note that I'm grabbing the underlying iframe DOM object.
I have tried below solution it works in all browser (IE/Chrome/Firefox)
Context: I want to focus the iframe all the time.
function IFocus() {
var iframe = $("#iframeId")[0];
iframe.contentWindow.focus();
};
window.setInterval(IFocus, 300);
Hope it helps, if any one in need...
I tested this solution with Chrome. I originally posted it in Setting focus to iframe contents.
Here is code to create an iframe using jQuery, append it to the document, poll it until it is loaded, then focus it. This is better than setting an arbitrary timeout which may or may not work depending on how long the iframe takes to load.
var jqueryIframe = $('<iframe>', {
src: "http://example.com"
}),
focusWhenReady = function(){
var iframe = jqueryIframe[0],
doc = iframe.contentDocument || iframe.contentWindow.document;
if (doc.readyState == "complete") {
iframe.contentWindow.focus();
} else {
setTimeout(focusWhenReady, 100)
}
}
$(document).append(jqueryIframe);
setTimeout(focusWhenReady, 10);
The code for detecting when the iframe is loaded was adapted from Biranchi's answer to How to check if iframe is loaded or it has a content?
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 !!!!!!!!!!!!!!!!
Can someone please help me out with printing the contents of an IFrame via a javascript call in Safari/Chrome.
This works in firefox:
$('#' + id)[0].focus();
$('#' + id)[0].contentWindow.print();
this works in IE:
window.frames[id].focus();
window.frames[id].print();
But I can't get anything to work in Safari/Chrome.
Thanks
Andrew
Here is my complete, cross browser solution:
In the iframe page:
function printPage() { print(); }
In the main page
function printIframe(id)
{
var iframe = document.frames
? document.frames[id]
: document.getElementById(id);
var ifWin = iframe.contentWindow || iframe;
iframe.focus();
ifWin.printPage();
return false;
}
Update: Many people seem to be having problems with this in versions of IE released since I had this problem. I do not have the time to re-investigate this right now, but, if you are stuck I suggest you read all the comments in this entire thread!
Put a print function in the iframe and call it from the parent.
iframe:
function printMe() {
window.print()
}
parent:
document.frame1.printMe()
I used Andrew's script but added a piece before the printPage() function is called. The iframe needs focus, otherwise it will still print the parent frame in IE.
function printIframe(id)
{
var iframe = document.frames ? document.frames[id] : document.getElementById(id);
var ifWin = iframe.contentWindow || iframe;
iframe.focus();
ifWin.printPage();
return false;
}
Don't thank me though, it was Andrew who wrote this. I just made a tweak =P
In addition to Andrew's and Max's solutions, using iframe.focus() resulted in printing parent frame instead of printing only child iframe in IE8. Changing that line fixed it:
function printIframe(id)
{
var iframe = document.frames ? document.frames[id] : document.getElementById(id);
var ifWin = iframe.contentWindow || iframe;
ifWin.focus();
ifWin.printPage();
return false;
}
I had to make few modifications in order to make it with in IE8 (didn't test with other IE flavours)
1) document.frames[param] seem to accept a number, not ID
printIframe(0, 'print');
function printIframe(num, id)
{
var iframe = document.frames ? document.frames[num] : document.getElementById(id);
var ifWin = iframe.contentWindow || iframe;
ifWin.focus();
ifWin.printPage();
return false;
}
2) I had a print dialog displayed upon page load and also there was a link to "Click here to start printing" (if it didn't start automatically). In order to get it work I had to add focus() call
<script type="text/javascript">
$(function(){
printPage();
});
function printPage()
{
focus();
print();
}
</script>
Use firefox window.frames but also add the name property because that uses the iframe in firefox
IE:
window.frames[id]
Firefox:
window.frames[name]
<img src="print.gif" onClick="javascript: window.frames['factura'].focus(); parent['factura'].print();">
<iframe src="factura.html" width="100%" height="400" id="factura" name="factura"></iframe>
One thing to note is if you are testing this locally using file:///, it will not work on chrome as the function in the iframe will appear as undefined. However once on a web server it will work.
You can use
parent.frames['id'].print();
Work at Chrome!
You can also use
top.iframeName.print();
or
parent.iframeName.print();
The 'framePartsList.contentWindow.print();' was not working in IE 11 ver11.0.43
Therefore I have used
framePartsList.contentWindow.document.execCommand('print', false, null);
In Chrome:
Press Ctrl+Shift+C to select the iframe.
Click anywhere in the iframe.
Go to the console tab and type window.print();
This works because in Chrome Dev Tools, the window element adjusts to whatever <html> context you are in.
Use this:
window.onload = setTimeout("window.print()", 1000);