Skip to content

Instantly share code, notes, and snippets.

@alnutile
Created January 11, 2014 00:57
Show Gist options
  • Save alnutile/8365567 to your computer and use it in GitHub Desktop.
Save alnutile/8365567 to your computer and use it in GitHub Desktop.
No name iframe
/**
* Sets an iFrame ID to no_name_iframe if there is no ID. You can then add a Switch to iFrame step after it using the na_name_iframe ID.
*
* @Given /^I the set the iframe located in element with an id of "([^"]*)"$/
*/
public function iSetTheIframeLocatedInElementWithAnIdOf($element_id) {
$check = 1; //@todo need to check using js if exists
if($check <= 0) {
throw new \Exception('Element not found');
} else {
$javascript = <<<JS
(function(){
var elem = document.getElementById('$element_id');
var iframes = elem.getElementsByTagName('iframe');
var f = iframes[0];
f.id = "no_name_iframe";
})()
JS;
$this->getMainContext()->getSession()->executeScript($javascript);
}
}
@lexcast
Copy link

lexcast commented Apr 29, 2015

thanks

@MaksymKrut
Copy link

Come up to this solution:

/**
 * @Given I switch to iframe with locator :locator
 * CSS, xPath values input
 * @param String $locator
 */
public function iSwitchToIFrameWithLocator($locator)
{
    $value = $this->takeValueFromIniFile('locators', $locator);
    $iframe = $this->getSession()->getPage()->find("css", $value);
    $iframeName = $iframe->getAttribute("name");

    if ($iframeName == "") {
        echo "\n\niFrame has no name. Let's name it.\n\n";
        $javascript = "(function(){
        console.log('JS code works. First line.');
        var iframes = document.getElementsByTagName('iframe');
        for (var i = 0; i < iframes.length; i++) {
            iframes[i].name = 'iframe_number_' + (i + 1) ;
        }
        })()";
        $this->getSession()->executeScript($javascript);
        $iframe = $this->getSession()->getPage()->find("css", $value);
        $iframeName = $iframe->getAttribute("name");
        echo "\n\niFrame has new name:  " . $iframeName . "\n\n";
    } else {
        echo "\n\niFrame already has a name: " . $iframeName . "\n\n";
    }

    $this->getSession()->getDriver()->switchToIFrame($iframeName);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment