How do I handle alerts in an Android web application using Appium server (1.0.1) and the Android SDK?
The below code is not working on android:
driver.switchTo().accept().alert();
Error message:
> -modal window does not get closed
How do I handle alerts in an Android web application using Appium server (1.0.1) and the Android SDK?
The below code is not working on android:
driver.switchTo().accept().alert();
Error message:
> -modal window does not get closed
The best way is to use the appium inspector. Click on the element and copy the resource-id from it. Use this resource id in findElement(By.id()) method.
For me resource-id: android:id/button1
((AndroidDriver) driver).findElement(By.id("android:id/button1")).click();
This is for Android. For regular use you can use
driver.findElement(By.id("android:id/button1")).click();
You need to get the Alert before you try and accept it
This is code from some of the Appium Java Client Tests:
wait.until(ExpectedConditions.alertIsPresent()); Alert alert = driver.switchTo().alert(); alert.accept();
This should work most of the time.
If accept()
isn't working, replace the driver.switchTo().alert();
and alert.accept();
with code to find the button and then click it.
If it's not finding the button wrap findElementBy(Method)
code in a try/retry block, and then click on it.
Some alerts may be native Android's alerts, not generated by a browser. In this case the following code:
Alert alert = driver.switchTo().alert(); alert.accept();
may throw: WebDriverException: unknown error: unhandled inspector error: {"code":-32603,"message":"No JavaScript dialog to handle"}
To handle such alert, just switch to the native application context, make required actions, and then switch back to the browser:
AppiumDriver appiumDriver = (AppiumDriver) webDriver; String currentContext = appiumDriver.getContext(); appiumDriver.context("NATIVE_APP"); // actions within the alert appiumDriver.findElements(By.xpath(OK_BUTTON_LOCATOR)).click(); // put locator instead of OK_BUTTON_LOCATOR appiumDriver.context(currentContext); // continue working
WebElement btn = driver.findElement(By.xpath("//android.widget.Button[@content-desc='OK']")); TouchAction act = new TouchAction(driver); act.tap(241,320).perform();
(241,320) these are X & Y c ordinates of alert This work perfectly for me
Appium comes with a default capability to accept, dismiss alerts
capabilities.SetCapability("autoAcceptAlerts", true); capabilities.SetCapability("autoDismissAlerts", true);
Please use the below code, Add some wait before clicking on OK Button. After that pass the xpath of you OK Button.
synchronized (driver) { driver.wait(2000); } driver.context(NATIVE_APP); driver.findElementByXPath{("//android.widget.Button[@resourceid= ‘android:id/button1’]").click();