问题
Writing test for an iFrame generated when a button is clicked. The iFrame name and id are similar but generated dynamically. I have used "switchToiFrame" successfully before.
<div class="bbbb-frame-container" style="height: 400px; width: 665px; margin-top: -200px; margin-left: -332.5px;">
<div class="user-support-frame-close-container" style="display: block;">
<div class="user-support-frame-close">Close</div>
</div>
<iframe id="poplock_default9636_priv" frameborder="0" name="poplock_default9636_priv" src="blah.blaag.com">
<!DOCTYPE html>
.....................
The poplock_defaultNNNN_priv is the dynamically generated iFrame that I would like to switch to..
回答1:
First, find an iframe with one of the find methods. If it's the only iframe on the page (or the first one) use the find() method
. If it's not, you'll have to use findAll()
and rely on the order (since there's no distinct attribute you could search for).
Once you find your iframe, you can use getAttribute to get its name and then use switchToIframe to... well, switch to the iframe.
回答2:
Thank you Jakub Zalas you inspired me for testing Stripe PopUp code which is embeded into an iframe.
Just for sharing my experience on testing a Stripe Payment PopUp:
$page = $this->getSession()->getPage();
$this->getSession()->getDriver()->switchToIFrame('stripe_checkout_app');
$page = $this->getSession()->getPage();
/** @var NodeElement $stripeInputField */
$stripeInputField = $page->findField($field); // where $field can be: 'Email, CVC, Card Number, MM / YY'
$emailInput->setValue($value);
// Switch Back to Main Window
$this->getSession()->getDriver()->switchToIFrame(null);
回答3:
If you need to simply manipulate the iFrame, see this question. The answers, for example, present Javascript to get the first iFrame so you can manipulate it:
window.frames[0].document.body.<your action here>
They also give jQuery examples for arbitrary iFrames:
<iframe id="my_iframe" ...></iframe>
$('#my_iframe').contents().find('html').html();
While those aren't exactly what you've asked for, you could alter them to find the n'th iFrame, if you know the number of iFrames generated and which you'd like to manipulate, and then manipulate it as need be.
回答4:
For whom it may help, to do the lookup for the dynamically named iframe I'm using the CSS selector on a known prefix:
// Switch to the payment iframe.
$iframe = $this->getSession()->getPage()->find('css', 'iframe[name^="__privateStripeFrame"]');
$iframe_name = $iframe->getAttribute('name');
$this->getSession()->switchToIFrame($iframe_name);
The CSS selector ^=
refers to "starts with ..." - instead, you can use *=
for "contains ..." if it is not a prefix.
This example is to get the Stripe 3D Secure popup.
来源:https://stackoverflow.com/questions/16445797/how-to-switch-to-dynamically-named-iframe-with-behat-mink