ArticleZip > Set Pupeteer Window Size When Running Not Headless Not Viewport

Set Pupeteer Window Size When Running Not Headless Not Viewport

When using Puppeteer for web scraping or automated testing, it's essential to set the window size when running the script in non-headless mode without specifying a viewport. Adjusting the window size can help ensure that the webpage renders correctly and that elements are visible without the need for a viewport setting.

By default, Puppeteer launches in headless mode, meaning that it runs in the background without a visible browser window. This is useful for tasks that don't require a browser interface. However, in some cases, you may need to run Puppeteer in non-headless mode to interact with the browser window. When running Puppeteer in non-headless mode without specifying a viewport, it's necessary to set the window size to ensure proper rendering.

To set the window size in Puppeteer when running in non-headless mode without a viewport, you can use the `setViewport` method along with the `setWindowSize` function. Here's how you can achieve this:

Javascript

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch({ headless: false });
  const page = await browser.newPage();

  await page.setViewport({ width: 1280, height: 800 }); // Set viewport size

  const client = await page.target().createCDPSession();
  await client.send('Emulation.clearDeviceMetricsOverride');

  await page.goto('https://www.example.com');
  
  // Set the window size
  await page.evaluate(() => {
    window.innerWidth = 1280;
    window.innerHeight = 800;
  });

  // Your Puppeteer scripting goes here

  await browser.close();
})();

In the code snippet above, we first launch Puppeteer in non-headless mode and create a new page. We then use the `setViewport` method to set the viewport size to 1280x800 pixels. Next, we access the Chrome DevTools Protocol (CDP) session to clear any device metrics override that may affect the window size.

After navigating to a webpage (replace `'https://www.example.com'` with the URL you want to visit), we use `page.evaluate` to set the window's inner width and height to 1280x800 pixels. This ensures that the window size matches the viewport dimensions we previously set.

By incorporating these steps into your Puppeteer script, you can successfully set the window size when running in non-headless mode without the need to explicitly define a viewport. This approach can help optimize your web scraping or testing automation tasks, ensuring that the webpage displays as intended during script execution.

Remember to tailor the window size values according to your specific requirements and adjust them as needed to achieve the desired display results. With these techniques, you can effectively control the window size in Puppeteer for a seamless browsing experience when operating in non-headless mode without specifying a viewport.

×