javascriptc#.netplaywrightplaywright-dotnet

Playwright dialog - how to display it?


Playwright auto-dismisses dialogs. Is there any way how to NOT dismiss it and actually display it?

To be clear -> When I open some website via chromium (var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions { Headless = false }); ...) and inject the js alert ("This is a warning message!"); nothing happens. Is there any way how to override playwright settings and display dialog?

Thanks


Solution

  • To handle dialogues in Playwright, we need to listen for the dialogue event and then interact with dialogue and prevent them for auto-dismissing. Attach an event listener to the page that listens for dialog events.

    const { chromium } = require('playwright');
    
    (async () => {
      // Launch the browser
      const browser = await chromium.launch({ headless: false });
      const context = await browser.newContext();
      const page = await context.newPage();
    
      // Attach an event listener to handle dialogs
      page.on('dialog', async dialog => {
        console.log(`Dialog message: ${dialog.message()}`);
        await dialog.accept(); // or dialog.dismiss();
      });
    
      // Navigate to your desired page
      await page.goto('https://example.com');
    
      // Inject an alert dialog using JavaScript
      await page.evaluate(() => alert('This is a warning message!'));
    
      await new Promise(resolve => setTimeout(resolve, 5000));
    
      await browser.close();
    })();