Как найти элемент в iframe

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

asked Jul 6, 2009 at 18:31

joepour's user avatar

joepourjoepour

6,80110 gold badges31 silver badges29 bronze badges

0

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

user's user avatar

user

14.3k6 gold badges25 silver badges120 bronze badges

answered Jul 6, 2009 at 18:35

geowa4's user avatar

geowa4geowa4

40.1k17 gold badges88 silver badges107 bronze badges

14

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>

answered Mar 14, 2017 at 9:44

lukyer's user avatar

lukyerlukyer

7,4353 gold badges37 silver badges31 bronze badges

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.

Community's user avatar

answered Apr 19, 2018 at 7:44

Lying_cat's user avatar

Lying_catLying_cat

1,2282 gold badges12 silver badges16 bronze badges

window.parent.document.getElementById("framekit").contentWindow.CallYourFunction('pass your value')

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

Roko C. Buljan's user avatar

answered Sep 19, 2014 at 12:36

VishalDream's user avatar

VishalDreamVishalDream

3113 silver badges6 bronze badges

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();

answered Aug 14, 2015 at 15:30

craned's user avatar

cranedcraned

2,9912 gold badges33 silver badges38 bronze badges

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.

answered Nov 23, 2020 at 21:44

Cary Meskell's user avatar

I have a webpage where there is a textarea within a iframe. I need to read the value of this textarea from its child page JavaScript. Presently by using window.parent.getelementbyID().value in the JavaScript, I am able to fetch values of all controls in the parent page except the textarea within the iframe.

The frame id and frame name in my parent page changes in runtime, hence we cannot use the frame id/frame name for reference.

Amir's user avatar

Amir

1,3182 gold badges13 silver badges27 bronze badges

asked Sep 21, 2009 at 4:12

archana roy's user avatar

3

If you have the HTML

<form name="formname" .... id="form-first">
    <iframe id="one" src="iframe2.html">
    </iframe>
</form>

and JavaScript

function iframeRef( frameRef ) {
    return frameRef.contentWindow
        ? frameRef.contentWindow.document
        : frameRef.contentDocument
}

var inside = iframeRef( document.getElementById('one') )

inside is now a reference to the document, so you can do getElementsByTagName('textarea') and whatever you like, depending on what’s inside the iframe src.

Owen Blacker's user avatar

Owen Blacker

4,1172 gold badges33 silver badges70 bronze badges

answered Sep 21, 2009 at 4:20

meder omuraliev's user avatar

meder omuralievmeder omuraliev

183k70 gold badges388 silver badges429 bronze badges

5

Using jQuery you can use contents(). For example:

var inside = $('#one').contents();

answered Jul 3, 2013 at 10:37

Doug Amos's user avatar

Doug AmosDoug Amos

4,2331 gold badge21 silver badges23 bronze badges

1

Есть страница, внутри нее iframe c id = «iframe-5».
Есть код и он не работает:

$('iframe#iframe-5').load(function(){
    $(this).contents().find('h1').remove();
});

Такой тоже:

$('iframe#iframe-5').contents().find('h1').remove();

Если брать console.log от $(‘iframe#iframe-5’).contents(), то объект имеет length:1, т.е. iframe вроде находит и берет его данные.

Но если брать console.log от $(‘iframe#iframe-5’).contents().find(‘h1’), то возвращается объект с length = 0. К примеру, такой:
Object { length: 0, prevObject: {…}, context: HTMLDocument somefakeurl.com/client/statistics, selector: «h1» }

если h1 заменить на любой друго тег или селектор — все то же самое.
h1 или img — все эти элементы есть внутри фрэйма.

Что я делаю не так?
Как «взять» элемент внутри iframe? Есть ли иные способы кроме contents()?
Что может блокировать? Apache security headers отключены.

This post shows you how to select an HTML Element inside an iframe using jQuery. The code looks in this way.

var iframe = $('#your-iframe');
iframe.on('load', function() {
    var iframeContents = $(this).contents();
    var element = iframeContents.find('selector');
})

Here an example showing how it works. First, create a simple sub-page.html, that will be displayed inside a iframe.

sub-page.html

<!DOCTYPE html>
<html>
<head>
    <title>Sub Page</title>
</head>
<body>
    <div id="message">This is sub page</div>
</body>
</html>

This sub-page.html page contains a div#message element, which we will try to get it later in jQuery code.

Then, create a parent-page.html with the following content. Click on the “Run Example” button to see how it works.

<!DOCTYPE html>
<html>
<head>
    <title>jQuery – Select an HTML Element inside an iFrame</title>
</head>
<body>
    <h4>iFrame:</h4>
    <iframe id="iframe1" src="https://bytenota.com/demos/demo-files/iframes/sub-page.html"></iframe>
	
    
    <h4>Content in iFrame:</h4>
    <div id="iframe-content"></div>


    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script type="text/javascript">
        
        $(function() {
            var iframe = $('#iframe1');
            iframe.on('load', function() {
                // iframe content
                var iframeContents = $(this).contents();

                // find #message in iframe contents
                var element = iframeContents.find('#message');

                // get element value
                var message = element.html();

                // display element value in view
                $('#iframe-content').html(message);
            })
        });

    </script>

</body>
</html>

Please note: We can’t access iframe with different origin because of security issue.

Cover image for Finding Elements in iframes with Selenium

Anyone who is using Selenium has encountered a scenario where they have to deal with an iframe.

There is no automatic way of detecting that the element you’re looking for is inside an iframe.

The error message only says ‘Element not found’.

You’re the one who’s going to have to look in the Browser Console and figure out that your element is inside an iframe.

Let’s create a test for the Stripe Payments Demo which has an iframe.

I’ll also be making some comparisons between Selenium and Endtest:

An iframe (inline frame) places another HTML document in a frame.

You need to change the focus of Selenium from one HTML document to another.

In our case, the only element which is inside the iframe is the Card input.

I used Python:

driver.get(«https://stripe-payments-demo.appspot.com»)

nameElement = driver.find_element_by_name(«name»)
emailElement = driver.find_element_by_name(«email»)
addressElement = driver.find_element_by_name(«address»)
cityElement = driver.find_element_by_name(«city»)
stateElement = driver.find_element_by_name(«state»)
zipElement = driver.find_element_by_name(«postal_code»)
countryElement = driver.find_element_by_name(«country»)
iframeElement = driver.find_element_by_name(«__privateStripeFrame5»)
cardElement = driver.find_element_by_name(«cardnumber)
submitButton = driver.find_element_by_css_selector(«#payment-form > button»)

nameElement.send_keys(«Klaus Werner»)
emailElement.send_keys(«klaus.werner@example.com»)
addressElement.send_keys(«Random Street»)
cityElement.send_keys(«San Francisco»)
stateElement.send_keys(«CA»)
zipElement.send_keys(«94107»)
countryElement.select_by_value(«US»)
driver.switch_to.frame(iframeElement)
cardElement.send_keys(«4111 1111 1111 1111»)
driver.switch_to.default_content()
submitButton.click()

Notice how I switched to the iframe before writing in the Card input?

And I also switched back to the main page after that.

It’s a bit easier to deal with iframes if you’re using Endtest:

Since you’re planning to run that test multiple times, you should generate a random email address and store it in a variable.

You can even test that email with the Endtest Mailbox

Понравилась статья? Поделить с друзьями:
  • Как найти цифровой пропуск по номеру
  • Как найти сумму средних линий треугольника
  • Как правильно найти ответ на задачу
  • Как составить бизнес план для малого бизнеса магазин продуктов
  • Как найти исходники сайта