简体   繁体   English

如何在 playwright-java 中切换到新选项卡或 window?

[英]How do I switch to new tab or window in playwright-java?

How can we switch to a new window that has opened while running test, and how can I get back to the parent window in playwright-java?我们如何切换到在运行测试时打开的新 window,以及如何在 playwright-java 中返回父 window?

There is no Switch action like Selenium.没有像 Selenium 这样的开关动作。 You can use the waitForPage or waitForPopup functions.您可以使用waitForPagewaitForPopup函数。 You just need to know what is the action triggering that new page.您只需要知道触发该新页面的操作是什么。 eg例如

Page popup = context.waitForPage(() -> page.click("a"));

The context class also has a pages() function, which returns all the open pages. context class 也有一个pages() function,它返回所有打开的页面。

expanding on @hardkoded's answer, I got an error and am now using this:扩展@hardkoded 的答案,我得到了一个错误,现在正在使用这个:

context.waitForEvent('page')

works for my purposes so far到目前为止适用于我的目的

What you want to do is continue your test in a new page.您要做的是在新页面中继续您的测试。 The official docs: https://playwright.dev/docs/pages#handling-new-pages官方文档: https://playwright.dev/docs/pages#handling-new-pages

Here is an example where we first work in the initial "page" and then, after clicking a button we want to continue our tests in a new tab we define as "newPage":这是一个示例,我们首先在初始“页面”中工作,然后单击按钮后,我们希望在定义为“newPage”的新选项卡中继续测试:

        // Here we are working in the initial page
        await page.locator("#locator").type("This happens in the initial page..");

        /*  When "Ok" is clicked the test waits for a new page event and assigns to new page object to a variable called newPage
            After this point we want the test to continue in the new tab,
            so we'll have to use the newly defined newPage variable when working on that tab
        */
        const [newPage] = await Promise.all([
            context.waitForEvent('page'),
            page.locator("span >> text=Ok").click()
            
        ])
        await newPage.waitForLoadState();

        console.log("A new tab opened and the url of the tab is: " + newPage.url());

        // Here we work with the newPage object and we can perform actions like with page
        await newPage.locator("#Description").type("This happens in a new tab!");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM