Skip to content

Instantly share code, notes, and snippets.

@jsteckel
Created September 18, 2012 09:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsteckel/3742281 to your computer and use it in GitHub Desktop.
Save jsteckel/3742281 to your computer and use it in GitHub Desktop.
WebDriver script that avoids UnreachableBrowserException
import org.junit.Before;
import org.junit.Test;
import org.junit.After;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.NoSuchElementException;
public class IframeTest
{
private WebDriver driver;
@Before
public void setUp() throws Exception
{
driver = new FirefoxDriver();
}
@Test
public void test() throws Exception
{
driver.get( "http://www.baur.de" );
switchToIframe( "layerEmailStart", "emailFormSubmit", 30000 );
new WebDriverWait( driver, 30 )
.until( ExpectedConditions.visibilityOfElementLocated( By.cssSelector( "input[type=\"submit\"]" )));
}
@After
public void tearDown() throws Exception
{
driver.quit();
}
public void switchToIframe( String iframeId, String elementId, long maxWaitInMillis ) throws Exception
{
long startTime = System.currentTimeMillis();
WebElement iframe = new WebDriverWait( driver, (int)( maxWaitInMillis / 1000 + 1 ) )
.until( ExpectedConditions.visibilityOfElementLocated( By.xpath( "//iframe[@id='" + iframeId + "']" )));
JavascriptExecutor js = (JavascriptExecutor) driver;
String script = "var myIframe = document.getElementById( '" + iframeId + "' );"
+ "var myIframeDoc = myIframe.contentDocument || myIframe.contentWindow.document;"
+ "var myElement = myIframeDoc.getElementById( '" + elementId + "' );"
+ "if ( !!myElement ) { return true; } else { return false; }";
do
{
if (( Boolean )js.executeScript( script ))
{
driver.switchTo().frame( iframe );
return;
}
Thread.sleep( 100 );
}
while ( System.currentTimeMillis() - startTime < maxWaitInMillis );
throw new TimeoutException( "Timeout after " + ( System.currentTimeMillis() - startTime ) + " ms. Target was " + maxWaitInMillis + " ms.",
new NoSuchElementException( "Could not locate element within iframe. Iframe ID: " + iframeId
+ ". Element ID: " + elementId + "."));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment