Reputation: 113
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?
Upvotes: 4
Views: 9977
Reputation: 29
It works fine for me:
String newUrl = page.context().pages().get(index_to_switch).url();
page.navigate(newUrl);
but you can also try this way:
page.context().pages().get(index_to_switch).bringToFront()
Upvotes: 2
Reputation: 44
Below code snippet works between tabs.
page.context().pages().stream().filter(x -> x.title().equals("expectedTitle")).findFirst().get().bringToFront();
Upvotes: 1
Reputation: 602
What you want to do is continue your test in a new page. The official docs: 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":
// 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!");
Upvotes: 0
Reputation: 715
expanding on @hardkoded's answer, I got an error and am now using this:
context.waitForEvent('page')
works for my purposes so far
Upvotes: 0
Reputation: 21695
There is no Switch action like Selenium. You can use the waitForPage
or waitForPopup
functions. You just need to know what is the action triggering that new page. e.g.
Page popup = context.waitForPage(() -> page.click("a"));
The context
class also has a pages()
function, which returns all the open pages.
Upvotes: 2