Skip to content

Instantly share code, notes, and snippets.

@sauceaaron
Created August 16, 2018 17:01
Show Gist options
  • Save sauceaaron/b2e73e205fd5501f179e766f757250ea to your computer and use it in GitHub Desktop.
Save sauceaaron/b2e73e205fd5501f179e766f757250ea to your computer and use it in GitHub Desktop.
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.remote.DesiredCapabilities;
import io.appium.java_client.AppiumDriver;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Set;
public class AppiumSwitchContextAndWindows
{
public String TESTOBJECT_ENDPOINT_US = "https://us1.appium.testobject.com/wd/hub";
public String TESTOBJECT_API_KEY = System.getenv("TESTOBJECT_API_KEY");
public String PLATFORM_NAME = "iOS";
public String PLATFORM_VERSION = "11.4";
public String DEVICE_NAME = "iPhone 8";
public String APPIUM_VERSION = "1.8.1";
AppiumDriver driver;
@Before
public void setup() throws MalformedURLException
{
URL url = new URL(TESTOBJECT_ENDPOINT_US);
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("platformName", PLATFORM_NAME);
capabilities.setCapability("platformVersion", PLATFORM_VERSION);
capabilities.setCapability("deviceName", DEVICE_NAME);
capabilities.setCapability("appiumVersion", APPIUM_VERSION);
capabilities.setCapability("testobject_api_key", TESTOBJECT_API_KEY);
driver = new AppiumDriver(url, capabilities);
}
@Test
public void checkContextAndWindows() throws Exception
{
String currentContext = driver.getContext();
if (currentContext.equals("NATIVE_APP"))
{
String webview = waitForWebView(driver, 60);
driver.context(webview);
System.out.println("Switched to WEBVIEW: " + webview);
}
Set<String> windows = driver.getWindowHandles();
String currentWindow = driver.getWindowHandle();
for (String window : windows)
{
if (window != currentWindow)
{
String newWindow = window;
driver.switchTo().window(newWindow);
System.out.println("Switched to WINDOW: " + newWindow);
}
}
}
@After
public void teardown()
{
if (driver != null)
{
driver.quit();
}
}
public String waitForWebView(AppiumDriver driver, int timeout) throws Exception
{
Set<String> contexts = driver.getContextHandles();
int counter = 0;
while (counter > timeout)
{
if (contexts.size() > 1)
{
return contexts
.stream()
.filter(context -> context.startsWith("WEBVIEW"))
.findFirst() // there could be more than one webview
.get();
}
Thread.sleep(1000);
}
throw new Exception("No WEBVIEW context found before timeout");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment