如何使用Playwright打开新标签页(例如,点击按钮可在新标签页中打开新部分)

时间:2020-10-09 09:19:07

标签: javascript node.js tabs webautomation playwright

我正在寻找一种针对当前情况的简单解决方案。例如,您打开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());

2 个答案:

答案 0 :(得分:1)

it('Open a new tab', async function () {
     await page.click(button, { button: "middle" });
     await page.waitForTimeout(); //waitForNavigation and waitForLoadState do not work in this case
     let pages = await context.pages();
     expect(await pages[1].title()).equal('Title');

答案 1 :(得分:0)

您可以将modifier传递给click函数。在macOS中,它将是Meta,因为您将使用cmd + click在新标签中打开。在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();