How can I run Puppeteer in non-headless mode in the background on macOS?

Puppeteer’s default behavior in non-headless mode is to bring the new Chrome window to the forefront, taking over the focus from the current application. Is there a way to keep Chrome open with headless: false, while ensuring it remains in the background or minimized? Alternatively, can I start it in an inactive desktop space to avoid disrupting my workflow, since macOS supports multiple desktops?

Running Puppeteer in non-headless mode without interrupting your workflow on macOS is a bit tricky, but you can use AppleScript to achieve this. Here's a concise way to keep it minimized:

const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch({ headless: false }); const page = await browser.newPage(); await page.goto('https://example.com'); // Execute an AppleScript to minimize the window const exec = require('child_process').exec; exec('osascript -e "tell application \"Google Chrome\" to set miniaturized of windows to true"'); })();

This script launches a non-headless Chrome and immediately minimizes it, helping you minimize disruptions.

While the solution provided by Alex_Brave using AppleScript is a practical approach, another alternative is to leverage macOS's native support for multiple desktops. This can keep Chrome in a different desktop space, allowing you to work uninterrupted in your current workspace.

Here's a slightly different take on achieving this:

  • Start by manually moving your Chrome browser to a different desktop space on macOS. You can use the Mission Control feature to create and switch between multiple desktops.
  • Use a Puppeteer script similar to the one below to open pages in non-headless mode:
const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch({ headless: false }); const page = await browser.newPage(); await page.goto('https://example.com'); // No AppleScript needed if you're okay with manual initial setup })();

In this method, perform the following steps:

  1. Set up your desktops via Mission Control.
  2. Drag your Chrome application to an alternate desktop.
  3. Once you run your Puppeteer script, it will open pages in the Chrome instance located on that specific desktop, keeping your current workspace distraction-free.

This approach needs manual desktop arrangement but can be quite effective once set up. For automated transitions between spaces, you may need to explore third-party automation tools specific to macOS.