I'm trying to create a printing function in javascript, it creates an iframe, sets the source and waits for the dom to be ready to print the contents of the iframe, but it's not working.
This is my function:
app.addReportPrintButtons = function (parentElement) {
var parent = parentElement || "body";
$(parent).on("click", ".print-report", function (e) {
var url = $(this).attr('href');
var iframe = document.createElement("IFRAME");
iframe.setAttribute("src", url);
iframe.onload = function (e) {
var win = iframe.contentWindow || iframe;
win.focus();
win.print();
};
e.preventDefault();
});
};
Can I print a page in a dynamically created iframe? or do the iframe needs to be attached to the DOM?
Javascript does not have the ability to print directly. It can only trigger the browser's print functionality. So if your element is not in the DOM, it can't be printed. In your code above, the iframe isn't printing because its not technically loaded until inserted in the DOM.
I recommend using CSS to hide the iframe with:
iframe {
display: none;
}
Put that in your regular screen stylesheet. Then in your print style sheet, show the iframe:
iframe {
display: block;
}
Related
I have the following iFrame:
<div id="sandbox-inner">
<iframe sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts" frameborder="0" name="Output " id="output" src="JavaScript:''"></iframe>
</div>
And when the user clicks to run their code, it injects the javascript successfully within this iframe. However, it actually runs it across the whole window, not just the iframe. So basically if I add a class "test" to an element outside the iframe, and one inside, and then inject the following inside the head of the iframe...
$(function() {
$('.test').css({ background: "blue" });
});
It effects my element outside the iframe too, which I really dont want. I need the iFrame to be a completely seperate environment. This is how I am currently injecting the javascript:
$('#runGuestCode').on("click", function () {
var js = $('#js-input').val(),
iframe = $("#output"),
iframeHead = iframe.contents().find("head").first(),
frame = document.getElementById("output"),
scriptTag = '<script>' + js + '<\/script>';
$('#output').contents().find("head").append(scriptTag);
});
Many thanks
UPDATE #1
The javascript is taken from textarea #js-input, which is whatever the user has typed. This is then appended to the head of the iframe, but currently runs relative to the parent document, not the iframe document.
You can do it following way, it will not effect you current page elements will apply to iframe element only:-
var iframe = $('iframe');
$(element, iframe.contents()).css({'background':'blue'});
Working Fiddle
Showcase the javascript code put by user in iframe:
$('#submit1').click(function (e) {
e.preventDefault();
var myIframe = document.getElementById("resultFrame");
var s = document.createElement("script");
s.type = "text/javascript";
s.innerHTML = $("#textarea1").val();
myIframe.contentWindow.document.head.appendChild(s);
});
Working Fiddle with Javascript Output in iframe
I've got this structure and I want to change the values of the form based on the form before. Problem is, the iframe got no ID and I can't set one as it is a plugin that retrieves the data from another domain.
...<input type="button" onclick="document.getElementById('betterplace').style.display='block';
var betterplace = document.getElementById('betterplace')[0];betterplace.getElementsByTagName('iframe')[0].document.getElementById('donation_presenter_address_first_name').value=document.getElementById('_vorname').value;
" style="border:none; height: 50px; width: 250px; font-weight:bold; font-size: 14pt; background-color:#94C119;color:white;cursor: pointer;" value="Ihre Spende abschließen"/>
<div id="betterplace" style="display:none;">
<div style="width:500px;height:2px;margin-bottom:5px;background-color: #94c119"/>
<br/>
<script type="text/javascript">
...
i can't understand your problem but if you want to insert some text or html into the iframe you can do this:
var iframe = document.getElementById('your iframe id') // if the iframe is already exists
doc, div;
doc = iframe.contentDocument || iframe.contentWindow.document;
doc.open();
doc.write('some text') // if you want to write to the iframe
doc.close();
div = doc.createElement('div');
// this div will appear in iframe
doc.body.appendChild(div)
Note: you can only manipulate iframe content if the iframe domain is the same as the domain of the main page
An example of dynamic creation of iframe:
var iframe = document.createElement('iframe'),
doc, div;
iframe.src = '' // same domain as main page
document.body.appendChild(iframe);
doc = iframe.contentDocument || iframe.contentWindow.document;
doc.open();
doc.write('some text') // if you want to write to the iframe
doc.close();
div = doc.createElement('div');
// this div will appear in iframe
div.appendChild(doc.createTextNode('im a div inside the iframe'));
doc.body.appendChild(div);
fiddle: here
Something like this will call the frame:
parent.frames[1].doWhatEver
All frames are put into an array, the first frame of your site will be parent.frames[0], the second parent.frames[1] and so on.
Edit:
If this does not work, you can always use this method:
parent.getElementsByTagName("iframe")[0].doWhatEver
// or
parent.getElementsByTagName("frame")[0].doWhatEver
getElementsByTagName(tagName) returns an array with elements that have the tagName (e.g. <iframe>). With this you can get your frame.
If it got no ID you have to draw it DOM path just analyze the path and get it in either JavaScript or JQUERY
I have a iFrame on my page thats display style is none. I have a javascript function to set the source and then set the display to block. The problem is that the iframe shows up before the content of it is loaded and thus I get a flickering effect. It goes white first and then displays the content. So I need to set the source, and when done loading all content of its source, only set its display style.
CSS & Javascript
.ShowMe{display:block;}
function(url)
{
document.getElementById('myIFrame').src = url;
document.getElementById('myIFrame').className = ShowMe;
}
It's simple as that:
<iframe onload="this.style.opacity=1;" style="opacity:0;border:none;
I would suggest you try the following:
<script type="javascript">
var iframe = document.createElement("myIFrame");
iframe.src = url;
if (navigator.userAgent.indexOf("MSIE") > -1 && !window.opera){
iframe.onreadystatechange = function(){
if (iframe.readyState == "complete"){
//not sure if your code works but it is below for reference
document.getElementById('myIFrame').class = ShowMe;
//or this which will work
//document.getElementById("myIFrame").className = "ShowMe";
}
};
}
else
{
iframe.onload = function(){
//not sure if your code works but it is below for reference
document.getElementById('myIFrame').class = ShowMe;
//or this which will work
//document.getElementById("myIFrame").className = "ShowMe";
};
}
</script>
Based on the code found here.
You could do this within the iframe:
window.onload = function () {
window.frameElement.className = 'ShowMe'; // 'ShowMe' or what ever you have in ShowMe variable.
}
Since you've tagged your question with [jquery], I assume you have executed the code within $(document).ready(). It is fired when the DOM is ready, i.e. it uses native DOMContentLoaded event (if available). window.onload is fired, when all resources on the page are ready.
I'm writing a firefox plugin who open an iframe in webpages. I want to select object in the iframe, but i can't access content:
var iframe = content.document.getElementById("MyBeautifulIframe");
if (iframe)
{
var mydiv = iframe.contentDocument.getElementById("mydiv");
}
Erreur : TypeError: iframe.contentDocument is undefined
I tryed with iframe.content.document.getElemen... , iframe.document.getElemen... same result.
How access iframe dom ? If i look iframe var type, it's [object XrayWrapper [object XULElement]], how access dom objects of XULElement object ?
Updated answer:
Took a look at your code and i think i may have found your problem.
You are doing:
var iframe = content.document.getElementById("muzich_iframe_addcontainer");
if (iframe)
{
if (iframe.contentDocument.getElementById("div"))
{
this.close_all();
}
}
muzich_iframe_addcontainer is a div, not the iframe, so it never has contentDocument.
Additionally, i couldn't make it work by creating xul elements. I had to create html div and iframe to make it work.
Here's the code:
var htmlns = "http://www.w3.org/1999/xhtml";
var container = document.createElementNS(htmlns,'div');
container.setAttribute("id", "muzich_iframe_addcontainer");
container.setAttribute("style", styleContainer); //styleContainer is the one you use without the background stuff
window.content.document.body.appendChild(container);
var iframe = document.createElementNS(htmlns,'iframe');
iframe.setAttribute("id", "muzich_iframe");
iframe.setAttribute("style",
"width: 100%; height: 100%; "
);
iframe.setAttribute("src", "http://www.lifehacker.com"); // Used it as my example url
window.content.document.getElementById("muzich_iframe_addcontainer").appendChild(iframe);
Then, when you want to check to close you do:
var iframe = window.content.document.getElementById("muzich_iframe");
if (iframe)
{
if (iframe.contentDocument.getElementById("div"))
{
this.close_all();
}
}
Hope this one solves it for you.
I'm dynamically creating an iframe and at some point I need to insert javascript into it. I can add the tag with the string just fine, but is there a way to force the iframe to re-evaluate its scripts so the javascript is executable?
Simple example of what needs to be done is, user provides:
<h2 onclick="doSomething();">Click me</h2>
and
function doSomething() { alert('you clicked me'); }
I need to push the html into the body of the iframe, and I need to push the javascript string into the scripts of the iframe in a way that will allow this to work.
HTML
<!--Container of iframe, iframe will be appended to this div later-->
<div id='myDiv'></div>
JS
var iframe = document.createElement('iframe');
iframe.frameBorder = 1;
iframe.width = "500px";
iframe.height = "250px";
iframe.id = "iframe";
iframe.onload = function()
{
var doc = iframe.contentDocument || iframe.contentWindow.document;
var el = doc.createElement('h2');
el.id="myH2";
el.className="red";
el.style.color="red";
el.style.cursor="pointer";
el.textContent = "Click me";
el.onclick=doSomething;
doc.body.appendChild(el);
}
document.getElementById("myDiv").appendChild(iframe);
function doSomething()
{
alert("OK");
}
Here is a fiddle.
If you change onclick="doSomething();" to onclick="top.doSomething(); it will work. Because copied h2 looks doSomething function on current window, and in iframe there is no doSomething function.
If you use top keyword, it will look function in top window. In iframe that means look for parent, and in parent look for self, and it will work in parent and in iframe either. Unless there is no another parent exists.