Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opening local HTML file using Puppeteer

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
like image 697
Anil Namde Avatar asked Dec 01 '17 05:12

Anil Namde


People also ask

How do I open a local file in HTML?

HTML 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.

How do I open a browser using puppeteer?

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).

Does puppeteer work with Chrome?

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.

How do I open puppeteer in Chrome?

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.


2 Answers

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

like image 45
Chuong Tran Avatar answered Sep 20 '22 11:09

Chuong Tran


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

like image 175
compound eye Avatar answered Sep 19 '22 11:09

compound eye