簡體   English   中英

如何接受不同窗口中出現的硒警報?

[英]How to accept alert in selenium which is coming up in a different window?

場景:有2個窗口打開。 當我單擊第二個窗口上的按鈕時,第三個窗口正在打開,焦點自動移至第三個窗口。 將在第三個窗口上發出警報以接受。

問題:由於警報來自其他窗口,因此我無法接受。

調查結果:我認為這是硒的局限性。 如果警報位於單擊按鈕的同一窗口中,則我們具有DOM,因此我們能夠與警報進行交互。 但是在這種情況下,警報位於另一個窗口中,因此瀏覽器的狀態被鎖定。

嘗試過的解決方案:通過使用javascript,硒行動類等嘗試了所有可能的方法,但是它不起作用。

一些嘗試的方法如下

//e.click();
                        /*Actions ac = new Actions(driver);

                        ac.sendKeys(Keys.ENTER).build().perform();*/
                        String onClickScript = "if(document.createEvent){var evObj = document.createEvent('MouseEvents');evObj.initEvent('click', true, false); arguments[0].dispatchEvent(evObj);} else if(document.createEventObject){ arguments[0].fireEvent('onclick');}";
                        JavascriptExecutor jse = (JavascriptExecutor)driver;
                        jse.executeScript(onClickScript, e);

                    /*  Actions asd = new Actions(driver);
                        asd.clickAndHold(e).perform();
                        Thread.sleep(1000);
                        asd.release().perform();*/

為了消除某些疑問, 警報是通過JavaScript生成的,並且絕不是HTML DOM的一部分。

接受關閉 警報,您必須始終誘使WebDriverWait使警報出現 ,如下所示:

import org.openqa.selenium.Alert;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
//other code
Alert myAlert = new WebDriverWait(driver, 10).until(ExpectedConditions.alertIsPresent());
//accept an alert
myAlert.accept();
//dismiss an alert
myAlert.dismiss();

下面的解決方案工作正常,可以在類似的情況下使用。

我們必須使用java.awt包的Robot類。 在下面的代碼中,Alt + space + c將關閉所有打開的窗口。 在這里關閉警報。

public void closeAlert(String strControlName, String delayTime) {
    Robot rb;
    int timeInSec = Integer.parseInt(delayTime);
    try {
        rb = new Robot();
        rb.keyPress(KeyEvent.VK_ENTER); //for clicking on the button or link
        rb.keyRelease(KeyEvent.VK_ENTER);
        Log.info("Wait for "+timeInSec+" Secs");
        Thread.sleep(timeInSec*1000);
        rb.keyPress(KeyEvent.VK_ALT); 
        rb.keyPress(KeyEvent.VK_SPACE);
        rb.keyPress(KeyEvent.VK_C);
        rb.keyRelease(KeyEvent.VK_C);
        rb.keyRelease(KeyEvent.VK_SPACE);
        rb.keyRelease(KeyEvent.VK_ALT); 
        Log.info("Successfully clicked on '"+strControlName+ "' and closed the Alert");
    } catch (Exception e) {
        Log.info("Failed click on '"+strControlName+ "' and close the Alert");
    }


}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM