Acess iframe content (in firefox plugin javascript) - javascript

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.

Related

How to traverse an HTML document loaded using iframe? [duplicate]

<iframe id="id_description_iframe" class="rte-zone" height="200" frameborder="0" title="description">
<html>
<head></head>
<body class="frameBody">
test<br/>
</body>
</html>
</iframe>
What I want to get is:
test<br/>
The exact question is how to do it with pure JavaScript not with jQuery.
But I always use the solution that can be found in jQuery's source code.
It's just one line of native JavaScript.
For me it's the best, easy readable and even afaik the shortest way to get the iframes content.
First get your iframe
var iframe = document.getElementById('id_description_iframe');
// or
var iframe = document.querySelector('#id_description_iframe');
And then use jQuery's solution
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
It works even in the Internet Explorer which does this trick during the contentWindow property of the iframe object. Most other browsers uses the contentDocument property and that is the reason why we proof this property first in this OR condition. If it is not set try contentWindow.document.
Select elements in iframe
Then you can usually use getElementById() or even querySelectorAll() to select the DOM-Element from the iframeDocument:
if (!iframeDocument) {
throw "iframe couldn't be found in DOM.";
}
var iframeContent = iframeDocument.getElementById('frameBody');
// or
var iframeContent = iframeDocument.querySelectorAll('#frameBody');
Call functions in the iframe
Get just the window element from iframe to call some global functions, variables or whole libraries (e.g. jQuery):
var iframeWindow = iframe.contentWindow;
// you can even call jQuery or other frameworks
// if it is loaded inside the iframe
iframeContent = iframeWindow.jQuery('#frameBody');
// or
iframeContent = iframeWindow.$('#frameBody');
// or even use any other global variable
iframeWindow.myVar = window.myVar;
// or call a global function
var myVar = iframeWindow.myFunction(param1 /*, ... */);
Note
All this is possible if you observe the same-origin policy.
Using JQuery, try this:
$("#id_description_iframe").contents().find("body").html()
it works perfectly for me :
document.getElementById('iframe_id').contentWindow.document.body.innerHTML;
AFAIK, an Iframe cannot be used that way. You need to point its src attribute to another page.
Here's how to get its body content using plane old javascript. This works with both IE and Firefox.
function getFrameContents(){
var iFrame = document.getElementById('id_description_iframe');
var iFrameBody;
if ( iFrame.contentDocument )
{ // FF
iFrameBody = iFrame.contentDocument.getElementsByTagName('body')[0];
}
else if ( iFrame.contentWindow )
{ // IE
iFrameBody = iFrame.contentWindow.document.getElementsByTagName('body')[0];
}
alert(iFrameBody.innerHTML);
}
use content in iframe with JS:
document.getElementById('id_iframe').contentWindow.document.write('content');
I think placing text inbetween the tags is reserved for browsers that cant handle iframes i.e...
<iframe src ="html_intro.asp" width="100%" height="300">
<p>Your browser does not support iframes.</p>
</iframe>
You use the 'src' attribute to set the source of the iframes html...
Hope that helps :)
Chalkey is correct, you need to use the src attribute to specify the page to be contained in the iframe. Providing you do this, and the document in the iframe is in the same domain as the parent document, you can use this:
var e = document.getElementById("id_description_iframe");
if(e != null) {
alert(e.contentWindow.document.body.innerHTML);
}
Obviously you can then do something useful with the contents instead of just putting them in an alert.
The following code is cross-browser compliant. It works in IE7, IE8, Fx 3, Safari, and Chrome, so no need to handle cross-browser issues. Did not test in IE6.
<iframe id="iframeId" name="iframeId">...</iframe>
<script type="text/javascript">
var iframeDoc;
if (window.frames && window.frames.iframeId &&
(iframeDoc = window.frames.iframeId.document)) {
var iframeBody = iframeDoc.body;
var ifromContent = iframeBody.innerHTML;
}
</script>
To get body content from javascript ,i have tried the following code:
var frameObj = document.getElementById('id_description_iframe');
var frameContent = frameObj.contentWindow.document.body.innerHTML;
where "id_description_iframe" is your iframe's id.
This code is working fine for me.
If you want to not just select the body of your iframe, but also insert some content to it, and do that with pure JS, and with no JQuery, and without document.write(), I have a solution that no other answer provides.
You can use the following steps
1.Select your iframe:
var iframe = document.getElementById("adblock_iframe");
2.Create an element that you want to insert into the frame, let's say an image:
var img = document.createElement('img');
img.src = "https://server-name.com/upload/adblock" + id + ".jpg";
img.style.paddingLeft = "450px";
//scale down the image is we have a high resolution screen on the client side
if (retina_test_media == true && high_res_test == true) {
img.style.width = "200px";
img.style.height = "50px";
} else {
img.style.width = "400px";
img.style.height = "100px";
}
img.id = "image";
3.Insert the image element into the iframe:
iframe.contentWindow.document.body.appendChild(img);
You can get the contents of the iframe body in one line of code:
document.getElementsByTagName('iframe')[0].contentWindow.document.body.innerText;

Load page in dynamically created iframe (not in dom) and print it

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;
}

Insert a value 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

Mobile Safari and iFrame src attribute

I am trying to set the 'src' attribute for an iFrame. It works great on FireFox and Internet Explorer. However, when testing on iPad mobile safari changing the 'src' attribute doesn't do anything.
I have an iFrame that has it's 'src' attribute set in the HTML.
<iframe id="iFrame0" style="margin: 0px; overflow: hidden; padding: 0px; height:80px; width:500px" src='.../loading.gif' frameborder="0"></iframe>
Later on I have some code that tries to change the src
var iFrame0 = YAHOO.util.Dom.get('iFrame0');
YAHOO.util.Event.addListener(iFrame0, 'load', function() { alert('test'); });
MyWebService.GetDynamicUrl('someparam', function(url) {
iFrame0.src = url;
});
Not only does the event not fire, but the content of the URL doesn't change. In my testing I noted that the value iFrame0.src does change to the newly passed in URL, but the content on the page does not change.
I am using YUI, however, to eliminate that as a potential problem in my testing I have also tried to directly access the iFrame via:
document.getElementById('iFrame0').attribute("src") = '..../newurl.gif';
Still doesn't work.
In the end I solved this by dynamically creating the iframe and attaching it to the DOM. I also added a timestamp to the id and src attributes in order ensure no caching is being done (though I'm unsure if that truly is necessary).
var elIFrame = document.createElement("iframe");
var dt = new Date();
elIFrame.src = APP_IMAGEPATH + "/loading.gif?dt=" + dt.getTime();
elIFrame.id = 'newCard2' + dt.getTime();
elIFrame.frameBorder = 0;
elIFrame.scrolling = "no";
elIFrame.style.width = "500px";
elIFrame.style.height = "1.8em";
YAHOO.util.Dom.insertAfter(elIFrame, this.pre + "cardMask");
Are you sure that the variable iFrame0 is actually pointing the iFrame DOM object and not some empty object or other element using the same ID (a DIV for example)? Maybe you could try to check the initial src to see if it's what you expect (i.e. '.../loading.gif').
Try to access the frame with the following:
var frameObj = document.frames ? document.frames['iFrame0'] : document.getElementById('iFrame0'),
frameWin = frameObj.contentWindow || frameObj;
And then try to modify its src:
frameWin.src = '..../newurl.gif';

How to get the body's content of an iframe in Javascript?

<iframe id="id_description_iframe" class="rte-zone" height="200" frameborder="0" title="description">
<html>
<head></head>
<body class="frameBody">
test<br/>
</body>
</html>
</iframe>
What I want to get is:
test<br/>
The exact question is how to do it with pure JavaScript not with jQuery.
But I always use the solution that can be found in jQuery's source code.
It's just one line of native JavaScript.
For me it's the best, easy readable and even afaik the shortest way to get the iframes content.
First get your iframe
var iframe = document.getElementById('id_description_iframe');
// or
var iframe = document.querySelector('#id_description_iframe');
And then use jQuery's solution
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
It works even in the Internet Explorer which does this trick during the contentWindow property of the iframe object. Most other browsers uses the contentDocument property and that is the reason why we proof this property first in this OR condition. If it is not set try contentWindow.document.
Select elements in iframe
Then you can usually use getElementById() or even querySelectorAll() to select the DOM-Element from the iframeDocument:
if (!iframeDocument) {
throw "iframe couldn't be found in DOM.";
}
var iframeContent = iframeDocument.getElementById('frameBody');
// or
var iframeContent = iframeDocument.querySelectorAll('#frameBody');
Call functions in the iframe
Get just the window element from iframe to call some global functions, variables or whole libraries (e.g. jQuery):
var iframeWindow = iframe.contentWindow;
// you can even call jQuery or other frameworks
// if it is loaded inside the iframe
iframeContent = iframeWindow.jQuery('#frameBody');
// or
iframeContent = iframeWindow.$('#frameBody');
// or even use any other global variable
iframeWindow.myVar = window.myVar;
// or call a global function
var myVar = iframeWindow.myFunction(param1 /*, ... */);
Note
All this is possible if you observe the same-origin policy.
Using JQuery, try this:
$("#id_description_iframe").contents().find("body").html()
it works perfectly for me :
document.getElementById('iframe_id').contentWindow.document.body.innerHTML;
AFAIK, an Iframe cannot be used that way. You need to point its src attribute to another page.
Here's how to get its body content using plane old javascript. This works with both IE and Firefox.
function getFrameContents(){
var iFrame = document.getElementById('id_description_iframe');
var iFrameBody;
if ( iFrame.contentDocument )
{ // FF
iFrameBody = iFrame.contentDocument.getElementsByTagName('body')[0];
}
else if ( iFrame.contentWindow )
{ // IE
iFrameBody = iFrame.contentWindow.document.getElementsByTagName('body')[0];
}
alert(iFrameBody.innerHTML);
}
use content in iframe with JS:
document.getElementById('id_iframe').contentWindow.document.write('content');
I think placing text inbetween the tags is reserved for browsers that cant handle iframes i.e...
<iframe src ="html_intro.asp" width="100%" height="300">
<p>Your browser does not support iframes.</p>
</iframe>
You use the 'src' attribute to set the source of the iframes html...
Hope that helps :)
Chalkey is correct, you need to use the src attribute to specify the page to be contained in the iframe. Providing you do this, and the document in the iframe is in the same domain as the parent document, you can use this:
var e = document.getElementById("id_description_iframe");
if(e != null) {
alert(e.contentWindow.document.body.innerHTML);
}
Obviously you can then do something useful with the contents instead of just putting them in an alert.
The following code is cross-browser compliant. It works in IE7, IE8, Fx 3, Safari, and Chrome, so no need to handle cross-browser issues. Did not test in IE6.
<iframe id="iframeId" name="iframeId">...</iframe>
<script type="text/javascript">
var iframeDoc;
if (window.frames && window.frames.iframeId &&
(iframeDoc = window.frames.iframeId.document)) {
var iframeBody = iframeDoc.body;
var ifromContent = iframeBody.innerHTML;
}
</script>
To get body content from javascript ,i have tried the following code:
var frameObj = document.getElementById('id_description_iframe');
var frameContent = frameObj.contentWindow.document.body.innerHTML;
where "id_description_iframe" is your iframe's id.
This code is working fine for me.
If you want to not just select the body of your iframe, but also insert some content to it, and do that with pure JS, and with no JQuery, and without document.write(), I have a solution that no other answer provides.
You can use the following steps
1.Select your iframe:
var iframe = document.getElementById("adblock_iframe");
2.Create an element that you want to insert into the frame, let's say an image:
var img = document.createElement('img');
img.src = "https://server-name.com/upload/adblock" + id + ".jpg";
img.style.paddingLeft = "450px";
//scale down the image is we have a high resolution screen on the client side
if (retina_test_media == true && high_res_test == true) {
img.style.width = "200px";
img.style.height = "50px";
} else {
img.style.width = "400px";
img.style.height = "100px";
}
img.id = "image";
3.Insert the image element into the iframe:
iframe.contentWindow.document.body.appendChild(img);
You can get the contents of the iframe body in one line of code:
document.getElementsByTagName('iframe')[0].contentWindow.document.body.innerText;

Categories