Search code examples
phpseleniumselenium-webdriverfancybox-2

setting iframe ID via fancybox2 to allow webdriver switchTo()->frame(id)


I'm using fancybox2 to create iframes but I can't see a way of setting the ID of the iframe that gets created, which is preventing me from using php-webdriver and selenium to test the contents of the iframe.

Simplified version of the code:

<a href="iframe.html" class="various fancybox.iframe">iframe</a>

<script>
$(document).ready(function() {
    $(".various").fancybox()
});
</script>

Which works, but using Chrome's inspector, the iframe was (this time) generated with an ID of fancybox-frame1443817733402, which appears to be random. This means when I try to use php-webdriver to switch to this frame (having clicked the link to create the iframe), I can't predict the frame's ID to pass in:

$frame_id = 'fancybox-frame1443817733402'; // can't predict this in advance
$driver->switchTo()->frame($frame_id);

The iframe is always generated with a class of fancybox-iframe but calls to

$iframe = $driver->findElement(WebDriverBy::class("fancybox-iframe"))

return nothing.

I've also tried using fancybox2's afterLoad callback to try explicitly setting the iframe's ID before trying to switch to the frame by this ID, but that also fails (I think because current is an object, not an element?)

$(".various").fancybox({
    afterLoad: function(current, previous) {
        //console.log(current);
        current.attr('id', 'rob');
    }});

Is there a way of explicitly setting the iframe's ID so that I can switch to it via selenium/webdriver? Or is there a simpler way of doing this?


Solution

  • I don't know about setting the frame id here, but you can switch to a frame via xpath (such as //frame):

        protected WebElement gotoIframeByXpath(final String iframeXpath) {
            if (driver.findElements(By.xpath(iframeXpath)).size() > 0) {  // find elements so an exception isn't thrown if not found
                WebElement contentFrame = driver.findElement(By.xpath(iframeXpath));
                driver.switchTo().frame(contentFrame);
                return contentFrame;
            } else {
                System.out.println("Unable to find " + iframeXpath);
            }
            return null;
        }