In Puppeteer-Sharp, which is the .NET port of the Puppeteer API, you can update the viewport size or device scale factor using the SetViewportAsync
method on a Page
object. This method allows you to define properties such as the width and height of the viewport, the device scale factor, and whether the screen should be set to emulate a mobile device.
Here's an example of how to update the viewport size and the device scale factor in Puppeteer-Sharp:
using System;
using System.Threading.Tasks;
using PuppeteerSharp;
class Program
{
static async Task Main(string[] args)
{
// Initialize PuppeteerSharp
await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
// Launch the browser
using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions
{
Headless = true // Set to false if you want to see the browser
}))
{
// Create a new page
using (var page = await browser.NewPageAsync())
{
// Set the viewport to 1920x1080 with a device scale factor of 1
await page.SetViewportAsync(new ViewPortOptions
{
Width = 1920,
Height = 1080,
DeviceScaleFactor = 1
});
// Go to a webpage
await page.GoToAsync("https://example.com");
// ... perform actions on the page ...
// If you need to change the viewport again later:
await page.SetViewportAsync(new ViewPortOptions
{
Width = 1280,
Height = 720,
DeviceScaleFactor = 2 // Increase the device scale factor
});
// ... perform more actions with the new viewport settings ...
// Close the page
await page.CloseAsync();
}
}
}
}
In this example, we set the initial viewport to 1920x1080 with a device scale factor of 1. Later in the code, we change it to 1280x720 with a device scale factor of 2.
Remember to handle exceptions and errors in your actual application code. This example omits error handling for brevity.
To use Puppeteer-Sharp, you'll need to install it via NuGet:
dotnet add package PuppeteerSharp
Make sure that you have the latest version of the package that is compatible with your project.
Finally, note that Puppeteer-Sharp is an asynchronous API, so you need to use the async
and await
keywords to work with the asynchronous methods like SetViewportAsync
.