How to apply page.EmulateAsync for all tabs, including those opened via clicks, in Puppeteer?

47 Views Asked by At

I'm using PuppeteerSharp to control a browser and set a mobile user agent for a page. However, when I click a link with target="_blank", the new tab loads in desktop mode, ignoring the emulation.

 var browser = await Puppeteer.LaunchAsync(new LaunchOptions()
 {
     ExecutablePath = $@"C:\Program Files\Google\Chrome\Application\chrome.exe",
     Headless = false,
     IgnoreHTTPSErrors = false
 });
 var page = await browser.NewPageAsync();
 DeviceDescriptor? deviceOptions = 
 Puppeteer.Devices.GetValueOrDefault(DeviceDescriptorName.IPhone11ProMax);
 await page.EmulateAsync(deviceOptions);
 await page.GoToAsync("https://example.com");

Is there a way to ensure page.emulateAsync (or a similar method) applies to all tabs, even those opened through link clicks with target="_blank"?

1

There are 1 best solutions below

0
hardkoded On BEST ANSWER

You can't set the emulation settings globally. But, you can listen to new pages and activate emulation in the event listener:

browser.TargetCreated += async (_, e) => 
{
  if (e.Target.TargetType == TargetType.Page)
  {
    var page = await e.Target.PageAsync();
    await page.EmulateAsync(deviceOptions);
  }
};