How can i switch between multiple webviews in each test

During my tests, I pass the Webview and interact with the related fields with the following code. Everything is fine until here.

Set<String> handles = ((AndroidDriver) getDriver()).getContextHandles();

    ((AndroidDriver) getDriver()).context((String) handles.toArray()[1]);

    Object[] windowHandles = getDriver().getWindowHandles().toArray();
    getDriver().switchTo().window(windowHandles[windowHandles.length - 3].toString());

    System.out.println("Current Context " + ((AndroidDriver) getDriver()).getContext());

then I switch context native and exit and closeApp

when I want to enter the same webview, I’m switching the context again as above. again and do another test operation. it does not enter the webview window I want.

how can i solve this problem thanks for your help.

I used a function:
* Switches focus to specified Context
* - web
* - native
* @param {string} context
async switchToContext(context)
const contexts = await driver.getContexts();
const view = contexts.filter((app) => app.includes(context.toUpperCase()));
if (view.length > 0)
await driver.switchContext(view[0]);
else { throw Error(${context} not found. Here are the options: ${contexts}); }

@Alvik Thanks for answer but I using java :confused:

this is an example of a hybrid app. you will have two active contexts, the native app and the webview app.
to know the names of the contexts

Set contexts = driver.getContextHandles();
for(String contextName : contexts) {

the context names are two NATIVE_APP and…
go to the context you want with:


here you write the steps you want for examples :

driver.pressKey(new KeyEvent(AndroidKey.BACK));

Then switch back with


This is just an example which you can try to adapt

Thanks for help, but My problem is not changing the context, I am making it happen. My problem is switching between different windows opened in the same webview.

I cannot stably switch between these tabs in the webview I switch to. @Giuma

@Aleksei any idea sir thanks.

you always switching to last - 3. which can be wrong. try print context names. Also context has some attributes like url and so on. This can help you to choose correct context. Not just - (last - 3).

Actually, I couldn’t find many examples. like printing name and url.

Can you give some examples please. @Aleksei

My webviews and windows like this. @Aleksei

ha I used it with ios. not android. with android not sure. with ios there is “fullContextList” capability that give more info. example

with android … and least try print context name and later try find same name to switch.

Actually I found this article,,getWindowHandles()%3B


But I didn’t understand where exactly to get from the html code of the page here. @Aleksei

this give you all texts that are in this view. so if you know what text should contain your view - it will help you to understand what view needed. For example you need view with “Tealium” text.