How to get the element inside an iframe element in Javascript? - javascript

I have a element as below inside the document, I could get the iframe element by document.getElementById('iframe_id'), but how to get the element inside this iframe? I tried iframeElement.contentWindow, and the returned DOMWindow has no properties. Also tried iframeElement.docuemnt and iframeElement.contentDocument, both of them are undefined. How can I get it? I am using the latest Chrome in my experiment.
Here is the iframe element
<iframe id='iframe_id'>
<html>
<body>many content here</body>
</html>
</iframe>

You can ONLY interrogate content in an iframe if the content has the same protocol, domain and port number as the script that interrogates it. It is called SAME ORIGIN
If that is the case, then this code will show the content. If not - you cannot access the iframe from a normal script in a normal html page
Demo - tested in IE8, Chrome 13 and Fx6
function showIframeContent(id) {
var iframe = document.getElementById(id);
try {
var doc = (iframe.contentDocument)? iframe.contentDocument: iframe.contentWindow.document;
alert(doc.body.innerHTML);
}
catch(e) {
alert(e.message);
}
return false;
}
<iframe id='iframe_id1' src="javascript:parent.somehtml()"> </iframe>
<br/>
Show
<hr/>
<iframe id='iframe_id2' src="http://plungjan.name/"> </iframe>
<br/>
Show
<hr/>

Having:
var iframe = document.getElementById('iframe_id');
To get the content document you can use:
var contDoc = iframe.contentDocument || iframe.contentWindow.document;
Then you can search for your element inside the iframe by id.

You should be able to access it by document.getElementById('yourIFrame').document.getElementById('yourElement')

Related

Why cant I access iframe's document with src or srcdoc attributes set?

<html>
<body>
<!-- <iframe id="iff" srcdoc="<div>ok</div>"></iframe> -->
<iframe id="iff" src="data:text/html;charset=utf-8,%3Cdiv%3Eok%3C%2Fdiv%3E"></iframe>
<script>
console.log(document.getElementById('iff').contentWindow.document)
</script>
</body>
</html>
I set srcdoc (tried src also) of <iframe>, but cannot access the real document of the iframe (tried iframeElement.contentDocument also). Chrome outputs (also tried Firefox):
I see in Get IFrame's document, from JavaScript in main document that I cannot get the document of a cross-domain iframe, and also learned from Which is the difference between srcdoc="..." and src="data:text/html,..." in an <iframe>? that src and srcdoc behaves different about cross-domain behavior. But I tried both, none works.
2. When I append a child to the document body of an iframe (with src attribute set), the DOM updates but it doesnt show on screen.
Try something like:
window.frames['iff'].document.myvar;
This can be useful if you look for the iframe with the url:
var x=getIframeID("cool.php");
x.contentWindow.callafunction();
function getIframeID(iframeurl) {
var iFs = top.document.getElementsByTagName('iframe');
var x, i = iFs.length;
while ( i-- ){
x = iFs[i];
if(iframeurl.indexOf(x.src)>=0) return (x.id);
if (x.src == iframeurl) return (x.id);
}
return("");
}

Access denied contentWindow iframe IE9

I have a page on www.domain.com and another page on sub.domain.com. sub.domain.com will be shown on www.domain.com in an iframe. I'm trying to dynamically calculate the height of this iframe based on the content of the iframe.
<iframe onload="calcHeight();" id="iframe" src="sub.domain.com"></iframe>
<script type="text/javascript">
function calcHeight()
{
//find the height of the internal page
document.domain = 'domain.com';
var the_height=parent.document.getElementById('iframe').contentWindow.document.body.scrollHeight +25;
//change the height of the iframe
parent.document.getElementById('iframe').height=the_height;
}
</script>
The src page DOES contain document.domain= 'domain.com';
It's working on all major browser besides IE9, which gives me an access denied on the javascript above. All solutions I read is dynamically adding the document.domain line to the iframe source, but as said, this is already in my static iframe source.
Whats wrong?
-edit-
Based on the suggestion I now have this on www.domain.com
<script type="text/javascript">
document.domain="domain.com";
</script>
<iframe style="border:0px;width:100%;" onload="calcHeight();" id="iframe" src="sub.domain.com"></iframe>
<script>
// IE hack
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE");
if (msie > -1) {
var source = "javascript:'<script>window.onload=function(){document.write(\\'<script>document.domain=\\\"" + document.domain + "\\\";<\\\\/script>\\');document.close();return \\\"+url+\\\";};<\/script>'";
$('#iframe').attr("src", source);
}
// End IE hack
function calcHeight()
{
//find the height of the internal page
var the_height=parent.document.getElementById('iframe').contentWindow.document.body.scrollHeight +25;
//change the height of the iframe
parent.document.getElementById('iframe').height=the_height;
}
</script>
-edit 2-
Based on the last remarks I now have this
<script type="text/javascript">
document.domain="domain.com";
url="sub.domain.com";
function calcHeight()
{
//find the height of the internal page
var the_height=parent.document.getElementById('iframe').contentWindow.document.body.scrollHeight +25;
//change the height of the iframe
parent.document.getElementById('iframe').height=the_height;
}
</script>
<iframe style="border:0px;width:100%;" onload="calcHeight();" id="iframe" src="javascript:'<script>window.onload=function(){document.write(\'<script>docum‌​ent.domain=\'domain.com\';<\\/script>\');document.close();return \'+url+\';};</script>'"></iframe>
Now I don't see the source page anymore.
Sorry, but because i had the same problem and i solved in this way can i ask you to try it exactly in this way:
var url = $('#iframe').attr("src");
if (isMSIE() == true) {
url = "javascript:'<script>window.onload=function(){document.write(\\'<script>document.domain=\\\"" + document.domain + "\\\";<\\\\/script>\\');document.close();return \\\"+url+\\\";};<\/script>'";
}
$('#iframe').attr("src", url);
The problem seems related to IE and what i did was to substitute the url whith a dynamic javascript that change the domain and return the url of iframe
Mainly, what happened to my customer was that the iframe appeared too little that is the motivatoin I used this approach:
Moreover the iframe from IE source:
<iframe width="300" class="vytmn-frame" id="iframe" src="javascript:'<script>window.onload=function(){document.write(\'<script>document.domain=\"localhost\";<\\/script>\');document.close();return \"+url+\";};</script>'" frameborder="0" scrolling="yes" horizontalscrolling="no" verticalscrolling="yes"></iframe>
In other words my problem was i to permit a full sized iframe because the iframe itself was shown by the browser too little and so invisible.
Sorry and I hope this time i gave you whaat i did.
It is unusefull to calculate the height: you have no access to the document inside the iframe. Sorry again.

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

get iframe page title from javascript using jquery

How to get iframe src page title and then set main page title
If you want to do it using jQuery:
var title = $("#frame_id").contents().find("title").html();
$(document).find("title").html(title);
You can do it only when pages are on the same domain, otherwise it's useless.
Granting that iframes src and the parent document src are the same domain:
Parent document:
<html>
<head><title>Parent</title>
<body>
<iframe id="f" src="someurl.html"></iframe>
<script>
//if the parent should set the title, here it is
document.title = document.getElementById('f').contentWindow.document.title;
</script>
</body>
</html>
someurl.html:
<html>
<head><title>Child</title>
<body>
<script>
//if the child wants to set the parent title, here it is
parent.document.title = document.title;
//or top.document.title = document.title;
</script>
</body>
</html>
Unless the webpage is in the iframe is from the same domain as the containing page, it is impossible.
If they do have the same domain, then try the following:
document.title = document.getElementById("iframe").documentElement.title;
One way you can share title and location:
document.write('<iframe src="http://www.yourwebsite.com/home.html?title='+document.title+'&url='+window.location+'" frameborder="0" scrolling="no"></iframe>');
and then you can read the parameters on home.html page.
This can be done using event listeners on the page. It's not particularly elegant, but the browsers I have tried it with support it (so IE9+, Firefox, Chrome).
In your main site page add the following javascript:
function setPageTitle(event) {
var newPageTitle = event.data
// your code for setting the page title and anything else you're doing
}
addEventListener('message', setPageTitle, false);
In the iFrame, you'll then need to have the following script:
var targetOrigin = "http://your.domain.com"; // needed to let the browser think the message came from your actual domain
parent.postMessage("New page title", targetOrigin); // this will trigger the message listener in the parent window

Get element from within an iFrame

How do you get a <div> from within an <iframe>?
var iframe = document.getElementById('iframeId');
var innerDoc = (iframe.contentDocument) ? iframe.contentDocument : iframe.contentWindow.document;
You could more simply write:
var iframe = document.getElementById('iframeId');
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
and the first valid inner doc will be returned.
Once you get the inner doc, you can just access its internals the same way as you would access any element on your current page. (innerDoc.getElementById...etc.)
IMPORTANT: Make sure that the iframe is on the same domain, otherwise you can't get access to its internals. That would be cross-site scripting. Reference:
MDN: <iframe> Scripting
MDN: Same-Origin Policy: Cross-Origin Script API Access
Do not forget to access iframe after it is loaded. Old but reliable way without jQuery:
<iframe src="samedomain.com/page.htm" id="iframe" onload="access()"></iframe>
<script>
function access() {
var iframe = document.getElementById("iframe");
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
console.log(innerDoc.body);
}
</script>
Above answers gave good solutions using Javscript.
Here is a simple jQuery solution:
$('#iframeId').contents().find('div')
The trick here is jQuery's .contents() method, unlike .children() which can only get HTML elements, .contents() can get both text nodes and HTML elements. That's why one can get document contents of an iframe by using it.
Further reading about jQuery .contents(): .contents()
Note that the iframe and page have to be on the same domain.
window.parent.document.getElementById("framekit").contentWindow.CallYourFunction('pass your value')
CallYourFunction() is function inside page and that function action on it
None of the other answers were working for me. I ended up creating a function within my iframe that returns the object I was looking for:
function getElementWithinIframe() {
return document.getElementById('copy-sheet-form');
}
Then you call that function like so to retrieve the element:
var el = document.getElementById("iframeId").contentWindow.functionNameToCall();
If iframe is not in the same domain such that you cannot get access to its internals from the parent but you can modify the source code of the iframe then you can modify the page displayed by the iframe to send messages to the parent window, which allows you to share information between the pages. Some sources:
https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
Html5 - Cross Browser Iframe postmessage - child to parent?
cross site iframe postMessage from child to parent
You can use this function to query for any element on the page, regardless of if it is nested inside of an iframe (or many iframes):
function querySelectorAllInIframes(selector) {
let elements = [];
const recurse = (contentWindow = window) => {
const iframes = contentWindow.document.body.querySelectorAll('iframe');
iframes.forEach(iframe => recurse(iframe.contentWindow));
elements = elements.concat(contentWindow.document.body.querySelectorAll(selector));
}
recurse();
return elements;
};
querySelectorAllInIframes('#elementToBeFound');
Note: Keep in mind that each of the iframes on the page will need to be of the same-origin, or this function will throw an error.
Below code will help you to find out iframe data.
let iframe = document.getElementById('frameId');
let innerDoc = iframe.contentDocument || iframe.contentWindow.document;

Categories