Contexts

In the initial chapter we discussed about the Native vs Hybrid app. In this chapter we will look at how to automate the Hybrid app. As we already discussed that a Hybrid App is a mobile app that combines elements of both native and web applications. It simply means you will have native elements and some features will be a web page inside a container. This container is known as Web view. It is typically developed using web technologies (like HTML, CSS, and JavaScript) but is wrapped in a native container.

To automate the elements inside these container you need to use web driver instead of appium driver. To put it simple words, you need to switch from appium driver to selenium web driver. This is done by switching context.

In the following example we will switch from a native context to webview context.

Java
C#
Python
Javascript
Kotlin
Copy
UiAutomator2Options options = new UiAutomator2Options();
options.setPlatformName("Android");
options.setDeviceName("Pixel_4_Emulator");
options.setAutomationName("UiAutomator2");
options.setApp("/path/to/your/app.apk");

URL appiumServerUrl = new URL("http://localhost:4723");
AndroidDriver driver = new AndroidDriver(appiumServerUrl, options);

// 1. Get all available contexts
Set<String> contexts = ((AndroidDriver) driver).getContextHandles();

// 2. Loop through contexts to find the webview
for(String context : contexts){
	if(context.contains("WEBVIEW")){

		// 3. Switch to the Webview context
		driver.context(context);
		break;
	}
}

// 4. Perform web automation here...
Assert.assertEquals(driver.findElement(By.tagName("h1")).getText(),"Hello, TAS!");

// 5. Switch back to Native context when done
driver.context("NATIVE_APP");

driver.quit();