java 我可以在Selenium WebDriver中检测浏览器何时手动关闭吗?

yeotifhr  于 2023-03-21  发布在  Java
关注(0)|答案(2)|浏览(213)

标题说明了一切。我想在WebDriver 4.8.1中侦听浏览器上的窗口关闭事件。我尝试查看WebDriverListener,但没有任何运气。以下是我的MCVE:

public class Test implements WebDriverListener {

    private Object lock = new Object();

    public Test() throws InterruptedException, MalformedURLException {
        WebDriver chrome = new ChromeDriver();
        EventFiringDecorator<WebDriver> decorator = new EventFiringDecorator<WebDriver>(this);
        WebDriver driver = decorator.decorate(chrome);

        driver.navigate().to(new URL("https://www.google.com/"));
        driver.manage().window().maximize();

        synchronized (lock) {
            lock.wait();
        }
    }

    public void beforeAnyWindowCall(Window window, Method method, Object[] args) {
        // Prints: maximize null
        System.out.println(method.getName() + " " + Arrays.toString(args));
    }

    public void beforeClose(WebDriver driver) {
        // Never is called
        System.out.println("Closing");
        synchronized (lock) {
            lock.notifyAll();
        }
    }

    public static void main(String[] args) throws InterruptedException, MalformedURLException {
        new Test();
        // Never is called
        System.out.println("Closed");
    }

}

在Swing中,我们有WindowListener#windowClosed(WindowEvent),它在窗口关闭时被触发。在Selenium WebDriver中可以完成类似的事情吗?澄清一下,我不是想知道WebDriver何时关闭,而是想知道 window 何时关闭。(手动)关闭。另外,我不是在寻找一个方法,我调用来确定 * 如果 * 窗口关闭。我想一个事件,以激发 * 当 * 关闭。
我看了下面的问题,但找不到一个有效的答案:

  1. How can I have Selenium ChromeDriver exit properly upon manually closing the window?
  2. Get browser closing event in selenium web browser
  3. How to determine when the browser is closed?
4urapxun

4urapxun1#

你可以使用下面的方法,当浏览器意外终止时,抛出UnreachableBrowserException异常

public boolean isBrowserClosed(WebDriver driver)
{
    boolean isClosed = false;
    try {
        driver.getTitle();
    } catch(UnreachableBrowserException e) {
        isClosed = true;
    }

    return isClosed;
}
6za6bjd0

6za6bjd02#

使用try-catch,如下所示:

driver.get("https://www.google.com");
        
try {
       System.out.println("Browser is open : " + driver.getWindowHandle());
    }  catch(Exception e) {
       System.out.println("Browser is closed");
    }
Thread.sleep(5000);
// closed the browser manually at this stage

try {
       System.out.println("Browser is open :" + driver.getWindowHandle());
    }  catch(Exception e) {
       System.out.println("Browser is closed");
    }

控制台输出:

Browser is open : CDwindow-540829C626B281B2E3F66CA5F7E169D4
Browser is closed

相关问题