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:
page.goto
: did not work with a local file or file://
.page.setContent
: is for an HTML stringHTML can be used to open a folder from our local storage. In order to open a folder from our local storage, use 'HREF' attribute of HTML. In the HREF attribute, we specify the path of our folder.
To use Puppeteer with a different version of Chrome or Chromium, pass in the executable's path when creating a Browser instance: const browser = await puppeteer. launch({ executablePath: '/path/to/Chrome' }); You can also use Puppeteer with Firefox Nightly (experimental support).
Puppeteer is a Node library which provides a high-level API to control headless Chrome or Chromium over the DevTools Protocol. It can also be configured to use full (non-headless) Chrome or Chromium.
Show activity on this post. I'd like to add, perhaps what you want is using the package chrome-launcher which takes care of running the chrome browser. You can then use puppeteer. connect() to connect the puppeteer-core library to the browser opened and instrument it.
If file is on local, using setContent will be better than goto
var contentHtml = fs.readFileSync('C:/Users/compoundeye/test.html', 'utf8'); await page.setContent(contentHtml);
You can check performance between setContent and goto at here
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With