how to handle alerts in android using appium

匿名 (未验证) 提交于 2019-12-03 01:58:03

问题:

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 

回答1:

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(); 


回答2:

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.



回答3:

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 


回答4:

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



回答5:

Appium comes with a default capability to accept, dismiss alerts

capabilities.SetCapability("autoAcceptAlerts", true); capabilities.SetCapability("autoDismissAlerts", true); 


回答6:

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(); 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!