如何将句柄切换到具有确认窗口的弹出窗口

时间:2019-10-21 02:42:29

标签: selenium webdriver

看看我的问题。

  1. root.html单击链接
  2. popup.html打开并确认窗口同时打开
  3. 我需要接受确认窗口,但无法切换到弹出窗口。

我正在尝试使用Selenium WebDriver编写测试代码。 测试用例之一,我需要接受确认窗口,但我不能。 我不是很酸,但是硒不能切换到已经确认的窗口。

ROOT.html

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>root window</title>
</head>
<body>
<script type="text/javascript">
  function orderpay() {
    var type = "popup";
    document.orderpay.poptype.value = type;
    paypop = window.open("about:blank", "orderpay", "width=620,height=550, scrollbars=yes").focus();
    document.orderpay.submit();
  }
</script>
<form name="orderpay" id="orderpay" action="./popup.html" method="post" target="orderpay">
    <input type="hidden" name="poptype"  value="">
</form>
<a href="javascript:orderpay();"> ::popup window open:: </a>
</body>
</html>

POPUP.html

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>popup window</title>
</head>
<script type="text/javascript">
 function showConfirm(){
  confirm("could you close me?");
  alert("this is alert window.");
 }
</script>
<body onload="showConfirm()">
<b>hello world</b>
</body>
</html>

测试代码

class ConfirmWindowTest {
    fun ifHasAlertClickOk(driver: WebDriver) {
        try {
            val alert = driver.switchTo().alert()
            alert.accept()
            sleep(1)
        } catch (e: Exception) {
            //e.printStackTrace()
        }
    }

    @Test
    fun closeConfirm() {
        var driver: WebDriver
        driver = ChromeDriver()
        driver.get("file:///{your file location}/root.html")

        //when this link click, popup.html will be opened
        driver.findElements(By.tagName("a")).first().click()

        //store root window handel
        val root = driver.windowHandle

        try {
            val handles = driver.windowHandles.filter { it != root }.toList()
            println(root)
            println(handles)
            handles.forEach {
                //I want to switch popup window and close confirm and alert but it doesn't work.
                driver.switchTo().window(it)

                ifHasAlertClickOk(driver)

                ifHasAlertClickOk(driver)

                println("ok it works")
            }
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            driver.switchTo().window(root)
        }
    }
}

现在它无法通过driver.switchTo().window(it), 但我想最终看到“确定”。

0 个答案:

没有答案
相关问题