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"
?
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);
}
};