Can Puppeteer load HTML files from local storage?

Hey everyone, I’m trying to figure out if there’s a way to use Puppeteer to open HTML files stored on my computer without setting up a web server. So far, I’ve only managed to get it working with a local server.

I looked at the Puppeteer docs and found two methods that seemed promising:

  1. page.goto(): This didn’t work when I tried using a local file path or file:// protocol.
  2. page.setContent(): This only takes HTML as a string, not a file.

Has anyone found a workaround for this? I’d really like to avoid setting up a server if possible. Any tips or tricks would be super helpful! Thanks in advance for your input.

In my experience, Puppeteer doesn’t directly load local HTML files without a server, but I found a workaround using Node’s fs module. I read the HTML file content with fs.readFileSync and then passed the content to page.setContent(). This method isn’t as direct as navigating to a file URL, and you need to handle relative paths for assets carefully. Despite these nuances, this approach has enabled me to automate tests on local HTML files without the overhead of setting up a web server.

hey, i think i got a solution for ya. try using the fs module to read ur HTML file, then use page.setContent() with the file contents. something like this:

const fs = require(‘fs’);
const html = fs.readFileSync(‘yourfile.html’, ‘utf8’);
await page.setContent(html);

just remember to fix any relative paths in ur HTML. hope this helps!

I’ve encountered this issue before, and while Puppeteer doesn’t natively support loading local HTML files, there’s a viable solution using Node.js file system operations. You can use the ‘fs’ module to read your local HTML file, then use page.setContent() with the file contents. Here’s a basic approach:

const fs = require(‘fs’);
const htmlContent = fs.readFileSync(‘path/to/your/file.html’, ‘utf8’);
await page.setContent(htmlContent);

This method bypasses the need for a server. However, be aware that relative paths for resources like images or stylesheets might not resolve correctly. You may need to adjust these paths or use page.evaluate() to modify the DOM after loading. It’s not perfect, but it’s a workable solution for many scenarios without involving a local server setup.