Rayrun
← Back to Discord Forum

Issue with closing tab

Hi! I have issue with closing tab 😦

shortstory:

  1. Go to the login page, fill credentails
  2. Open in new tab mail provider and get 2fa code
  3. Close 2nd tab
  4. Fill 2fa code

And after run test I see that closing isn work (point 3):) My code:

const mailCatcherPage = await this.browserContext.newPage();
    await mailCatcherPage.goto(this.getUrl('messages'));

    do {
      const emails = JSON.parse(await mailCatcherPage.locator('pre').first().textContent()) as Email[];
      numberOfElements = emails.length;

      await mailCatcherPage.waitForTimeout(SHORT_WAIT_TIME);
      await mailCatcherPage.reload();
    } while (numberOfElements < expectedNumberOfEvents);

    await mailCatcherPage.close()```


And the last line do nothing.
`browserContext:: (this.page.context())`


any ideas how to close this tab with mailcatcher?

This thread is trying to answer question "How can I close the mailCatcherPage tab in my code?"

0 replies

Answer

Closing a Page in Playwright

Closing a page in Playwright is straightforward. You just need to call the page.close() method. This method will close the page and wait for it to actually close.

However, there's a case where page.close() doesn't wait for the page to close. This happens when you pass a truthy value for the runBeforeUnload option.

Handling Dialogs Before Closing

Before closing a page, you might encounter dialogs. To handle these, you can register a dialog handler using page.on('dialog', dialog => {}). Inside this handler, check if the dialog type is 'beforeunload' and then dismiss it using dialog.dismiss().

Here's how you can do it:

import { chromium } from 'playwright';

async function closePage() {
  const browser = await chromium.launch();
  const context = await browser.newContext();
  const page = await context.newPage();

  // Register dialog handler
  page.on('dialog', async (dialog) => {
    if (dialog.type() === 'beforeunload') {
      await dialog.dismiss();
    }
  });

  // Close the page with runBeforeUnload option set to true
  await page.close({ runBeforeUnload: true });

  // Close browser
  await browser.close();
}

closePage().catch(console.error);

In this code, we first launch a Chromium browser, create a new context, and open a new page. Then we register a dialog handler where we check if the dialog type is 'beforeunload' and dismiss it.

Finally, we close the page while handling any beforeunload dialogs and close the browser.

Remember, this code is a general example and may need to be adapted to your specific use case. Happy testing with Playwright!

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].