Table of contents

How do I update the viewport size or device scale factor in Puppeteer-Sharp?

Setting Viewport Size and Device Scale Factor

In Puppeteer-Sharp, you can control how your browser page renders by adjusting the viewport size and device scale factor using the SetViewportAsync method. This is essential for responsive design testing, mobile emulation, and ensuring your web scraping works across different screen configurations.

Basic Viewport Configuration

The SetViewportAsync method accepts a ViewPortOptions object with several important properties:

  • Width: Viewport width in pixels
  • Height: Viewport height in pixels
  • DeviceScaleFactor: Device pixel ratio (defaults to 1)
  • IsMobile: Whether to emulate mobile behavior
  • HasTouch: Whether to enable touch events
  • IsLandscape: Screen orientation

Installation

First, install Puppeteer-Sharp via NuGet:

dotnet add package PuppeteerSharp

Complete Example

using System;
using System.Threading.Tasks;
using PuppeteerSharp;

class Program
{
    static async Task Main(string[] args)
    {
        try
        {
            // Download browser if needed
            await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);

            // Launch browser
            using var browser = await Puppeteer.LaunchAsync(new LaunchOptions
            {
                Headless = true
            });

            using var page = await browser.NewPageAsync();

            // Set desktop viewport (1920x1080, standard DPI)
            await page.SetViewportAsync(new ViewPortOptions
            {
                Width = 1920,
                Height = 1080,
                DeviceScaleFactor = 1
            });

            await page.GoToAsync("https://example.com");

            // Take screenshot with desktop viewport
            await page.ScreenshotAsync("desktop-view.png");

            // Switch to mobile viewport with high DPI
            await page.SetViewportAsync(new ViewPortOptions
            {
                Width = 375,
                Height = 812,
                DeviceScaleFactor = 2,
                IsMobile = true,
                HasTouch = true
            });

            // Reload to see mobile layout
            await page.ReloadAsync();
            await page.ScreenshotAsync("mobile-view.png");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}

Device Emulation Examples

iPhone 13 Pro Emulation

await page.SetViewportAsync(new ViewPortOptions
{
    Width = 390,
    Height = 844,
    DeviceScaleFactor = 3,
    IsMobile = true,
    HasTouch = true
});

iPad Emulation

await page.SetViewportAsync(new ViewPortOptions
{
    Width = 820,
    Height = 1180,
    DeviceScaleFactor = 2,
    IsMobile = true,
    HasTouch = true,
    IsLandscape = false
});

4K Desktop Display

await page.SetViewportAsync(new ViewPortOptions
{
    Width = 3840,
    Height = 2160,
    DeviceScaleFactor = 1
});

Getting Current Viewport

You can retrieve the current viewport settings:

var viewport = page.Viewport;
Console.WriteLine($"Current viewport: {viewport.Width}x{viewport.Height}, DPR: {viewport.DeviceScaleFactor}");

Best Practices

  1. Set viewport before navigation: Always configure the viewport before navigating to pages for consistent results
  2. Match real devices: Use actual device dimensions for accurate mobile testing
  3. Consider device scale factor: High-DPI displays (Retina, etc.) typically use scale factors of 2 or 3
  4. Test responsive breakpoints: Common breakpoints include 320px, 768px, 1024px, and 1920px widths
  5. Handle exceptions: Wrap viewport operations in try-catch blocks for robust error handling

Common Use Cases

  • Responsive design testing: Verify layouts work across different screen sizes
  • Mobile-first development: Test mobile layouts and touch interactions
  • Web scraping: Ensure scraped content renders correctly on target devices
  • Screenshot generation: Create consistent screenshots for documentation or testing
  • Performance testing: Measure page load times across different viewport configurations

The viewport configuration affects how CSS media queries are evaluated and how the page layout renders, making it crucial for accurate web testing and automation.

Try WebScraping.AI for Your Web Scraping Needs

Looking for a powerful web scraping solution? WebScraping.AI provides an LLM-powered API that combines Chromium JavaScript rendering with rotating proxies for reliable data extraction.

Key Features:

  • AI-powered extraction: Ask questions about web pages or extract structured data fields
  • JavaScript rendering: Full Chromium browser support for dynamic content
  • Rotating proxies: Datacenter and residential proxies from multiple countries
  • Easy integration: Simple REST API with SDKs for Python, Ruby, PHP, and more
  • Reliable & scalable: Built for developers who need consistent results

Getting Started:

Get page content with AI analysis:

curl "https://api.webscraping.ai/ai/question?url=https://example.com&question=What is the main topic?&api_key=YOUR_API_KEY"

Extract structured data:

curl "https://api.webscraping.ai/ai/fields?url=https://example.com&fields[title]=Page title&fields[price]=Product price&api_key=YOUR_API_KEY"

Try in request builder

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon