繁体   English   中英

如何使用 Playwright 打开新选项卡(例如单击按钮在新选项卡中打开新部分)

[英]How to open the new tab using Playwright (ex. click the button to open the new section in a new tab)

我正在寻找针对当前情况的更简单的解决方案。 例如,您打开谷歌(任何其他网站)并希望通过单击按钮(例如 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(); //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+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();

在我的例子中,我在弹出窗口中单击链接,例如( 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

现在剧作家文档中提到等待新页面,复制如下:

// 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());

暂无
暂无

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

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