我如何处理 playwright-java 中的弹出窗口?

How can i handle popups in playwright-java?

我如何处理 playwright 中的警报和弹出窗口-java? API 中有不同的方法,如 page.onDialog()、page.onPopup(),它们之间有什么区别以及如何生成句柄?

//code to launch my browser and url
            Playwright playwright = Playwright.create();
            Browser browser = playwright.chromium().launch(new LaunchOptions().withHeadless(false).withSlowMo(50));
            BrowserContext context = browser.newContext();
            Page page = context.newPage();
            page.navigate("http://myurl.com");
    
//had to switch to iframe to click on upload button
            Frame mypage = page.frameByName("uploadScreenPage");
    
//below line is triggering the alert
            mypage.setInputFiles("//*[@id='fileUpload']",Path.of("C:\myFile.jar"));
            
//using this code to handle alert, which is not working
            page.onDialog(dialog -> {dialog.accept();});

无法使用上述代码接受警报。单击 iframe 内的元素后也会出现警报。我该如何处理此类警报?

Dialog 是类似 alert or a confirm, whereas popups are new pages, like the one you would get by calling window.open 的消息。

您可以这样使用它:

page.onDialog(dialog -> {
    assertEquals("alert", dialog.type());
    assertEquals("", dialog.defaultValue());
    assertEquals("yo", dialog.message());
    dialog.accept();
});
page.evaluate("alert('yo')");
//listening to the alert
page.onDialog(dialog -> {dialog.accept();});

//next line will be action that triggers your alert
page.click("//['clickonsomethingthatopensalert']")

很高兴回答这个问题。我遇到了同样的情况并找到了解决方案。请看下面:

//处理弹窗或新页面

Page pgdriver1 = pagedriver.waitForPopup(new Runnable()
{
        public void run() {
        pagedriver.click("text=\"Analiza\""); 
        }
    });

pgdriver1.click("//button[normalize-space(@aria-label)=\"Close dialog\"]/nx-icon"); 

我希望这能回答你的问题。