Opening local HTML file using Puppeteer

Anil Namde picture Anil Namde · Dec 1, 2017 · Viewed 26.5k times · Source

Is it possible to open a local HTML file with headless Chrome using Puppeteer (without a web server)? I could only get it to work against a local server.

I found setContent() and goto() in the Puppeteer API documentation, but:

  1. page.goto: did not work with a local file or file://.
  2. page.setContent: is for an HTML string

Answer

compound eye picture compound eye · Dec 5, 2017

I just did a test locally (you can see I did this on windows) and puppeteer happily opened my local html file using page.goto and a full file url, and saved it as a pdf:

'use strict';

const puppeteer = require('puppeteer');    
(async() => {    
const browser = await puppeteer.launch();
const page = await browser.newPage();    
await page.goto('file://C:/Users/compoundeye/test.html');    
await page.pdf({
  path: 'test.pdf',
  format: 'A4',
  margin: {
        top: "20px",
        left: "20px",
        right: "20px",
        bottom: "20px"
  }    
});    
await browser.close();    
})();

If you need to use a relative path might want to look at this question about the use of relative file paths: File Uri Scheme and Relative Files