Search code examples
phpseleniumiframephpunit

How to switch to iframe in selenium PHP unit


I want to write test to login in a site. The problem is when I click in Login a pop up is appeared which is an iframe. Now I write code to switch between the window. But I switch in different iframe. I don't know where it coming from Here is a snippet of code. I use selenium WebDriver written by Facebook.

<?php
class TitleTest extends PHPUnit_Framework_TestCase {

protected $webDriver;
public function setUp()
{
    $capabilities = array(\WebDriverCapabilityType::BROWSER_NAME => 'firefox');
    $this->webDriver = RemoteWebDriver::create('http://ip-address:4444/wd/hub', $capabilities);
}
protected $url = 'https://mywebsite.net';

public function testAfterLoginBudliTitle()
{
    // Sell used Login and account page's title assert
    $this->webDriver->get($this->url);
    $this->webDriver->manage()->window()->maximize();
    $link = $this->webDriver->findElement(WebDriverBy::xpath('/html/body/div[3]/header/div[2]/div/ul/li[2]/a'));
    sleep(2);        
    $link->click(); //click on login
    sleep(3);
    $iframe = $this->webDriver->findElement(WebDriverBy::tagName('iframe'));

    $frameName = $iframe->getAttribute('name');
    //Switch the driver to the iframe
    $this->webDriver->switchTo()->frame($frameName);
    $this->assertContains('demo', $frameName); // Here I get the different iframe name
 }  
}
?>

Solution

  • In order to interact with elements inside a frame or iframe, switch to that frame first!

    $my_frame = 'id_or_name';
    $driver->switchTo()->frame($my_frame);
    
    // do your stuff here and switch back afterwards
    
    $driver->switchTo()->defaultContent();
    

    See the wiki. https://github.com/facebook/php-webdriver/wiki/Alert,-Window-Tab,-frame-iframe-and-active-element#frame-iframe