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
Related
<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;
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.
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')
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;