Get element from within an iFrame
Asked Answered
F

7

317

How do you get a <div> from within an <iframe>?

Freytag answered 6/7, 2009 at 18:31 Comment(0)
M
485
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:

Mazel answered 6/7, 2009 at 18:35 Comment(14)
Great answer. Did you know that you can do: var innerDoc = iframe.contentDocument || iframe.contentWindow.document; //more readable and means the sameFarley
I've seen people confused by that more than ternary operators. They seem to not know that the first valid one is returned.Mazel
in fact, as i edited the answer to include it, the guy over my shoulder asked me what that did...Mazel
Probably better to educate than use more complex code for simplicity :)Farley
I know and found the above answer is correct, but while doing innerDoc.getElementById("idab") I got an error like "Error: Permission denied to access property 'getElementById'". Do you know why this error came.Aprilette
I also get an error (in Chrome) when trying to access an Element in an iframe whose domain differs from the top page. Any way around this?Violative
@JellicleCat: Any way around that is a way to do "Cross-site request forgery", also known as "one-click" attack or "session riding"Rapper
sometimes trying to get the content of the iframe returns null, be sure to check for that.Psychosurgery
While this may error out on a hosted page, running a local file in the browser with this code worked, at least on Safari and a publicly shared printer's web server.Rhapsodic
What's the difference between iframe.contentDocument and iframe.contentWindow.document?Achlamydeous
@StevenM.Vascellaro Cross browserMisstate
Is it possible to do cross-site scripting?? i wanna do a scrapper...Edibles
Is there a way to get access to the iframe internals if the iframe originates from a different URL. You mentioned that it is cross-site scripting, but I am wondering if there is a way.Valerio
@FabianAmran If there was a way all PHP applications that use hidden input fields for csrf tokens would be hacked to the ground by nowPrecipitation
L
21

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>
Leopoldeen answered 14/3, 2017 at 9:44 Comment(0)
W
12

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.

Wearproof answered 19/4, 2018 at 7:44 Comment(0)
C
7
window.parent.document.getElementById("framekit").contentWindow.CallYourFunction('pass your value')

CallYourFunction() is function inside page and that function action on it

Cornett answered 19/9, 2014 at 12:36 Comment(1)
That's calling a function from an iFrame, not getting a reference to the element.Theolatheologian
E
1

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();
Estimate answered 14/8, 2015 at 15:30 Comment(0)
P
0

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:

Pylle answered 20/3, 2019 at 21:22 Comment(0)
S
0

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.

Selle answered 23/11, 2020 at 21:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.