我正在寻找针对当前情况的更简单的解决方案。例如,您打开 google(任何其他网站),并且希望通过单击按钮(例如 Gmail)- 使用 Playwright 在新选项卡中打开此页面。
let browser, page, context;
describe('Check the main page view', function () {
before(async () => {
for (const browserType of ['chromium']) {
browser = await playwright[browserType].launch({headless: false});
context = await browser.newContext();
page = await context.newPage();
await page.goto(baseUrl);
}
});
after(async function () {
browser.close();
});
await page.click(tax);
const taxPage = await page.getAttribute(taxAccount, 'href');
const [newPage] = await Promise.all([
context.waitForEvent('page'),
page.evaluate((taxPage) => window.open(taxPage, '_blank'), taxPage)]);
await newPage.waitForLoadState();
console.log(await newPage.title());
it('Open a new tab', async function () {
await page.click(button, { button: "middle" });
await page.waitForTimeout(2000); //waitForNavigation and waitForLoadState do not work in this case
let pages = await context.pages();
expect(await pages[1].title()).equal('Title');
您可以将
modifier
传递给 click
函数。在 Macos 中,它会是 Meta
,因为您将使用 cmd+单击在新选项卡中打开。在 Windows 中,它会是 Control
。
const browser = await playwright["chromium"].launch({headless : false});
const page = await browser.newPage();
await page.goto('https://www.facebook.com/');
var pagePromise = page.context().waitForEvent('page', p => p.url() =='https://www.messenger.com/');
await page.click('text=Messenger', { modifiers: ['Meta']});
const newPage = await pagePromise;
await newPage.bringToFront();
await browser.close();
等待新页面现在在playwright文档中提到,复制如下:
// Start waiting for new page before clicking. Note no await.
const pagePromise = context.waitForEvent('page');
await page.getByText('open new tab').click();
const newPage = await pagePromise;
await newPage.waitForLoadState();
console.log(await newPage.title());
就我而言,我单击弹出窗口中的链接(ctrl + 单击链接),然后它会打开新选项卡并在该新选项卡上工作
await page.click('#open')
const [newTab] = await Promise.all([
page.waitForEvent('popup'),
await page.keyboard.down('Control'),
await page.frameLocator('//iframe[@title="New tab."]').locator('a').click(), // in popup
await page.keyboard.up('Control'),
console.log("clicked on link")
]);
await newTab.waitForFunction(()=>document.title === 'new tab title')
await newTab.fill('#firstname')
await newTab.close() // close the current tab
await page.click('#exitbutton') //back to parent tab and work on it
....
....
await page.close() // close the parent tab
const pages = await this.page.context().pages();
return pages[1]; // Return an opened tab
如果您想切换到旧选项卡,则无需执行任何操作,即可继续使用旧页面对象。但是,如果您想切换到该选项卡以查看那里发生的情况:
await oldTabPageObject.page.bringToFront();
await page.waitForTimeout(2000);
,这会导致测试随着时间的推移变得不稳定。触发链接点击或打开页面后,您可以立即从
waitForEvent(page)
实例中使用 BrowserContext
。
async loadNewPage() {
const pagePromise = this.context.waitForEvent('page');
const newPage = await pagePromise;
await newPage.waitForLoadState();
return newPage
}