tl;dr there are caveats using page.setContent()
in blank page
As noted by other answers, you can read the file using a Node API and then call page.setContent()
for more flexibility over page.goto()
. However, there are some limitations when the about:blank (default) page is displayed such as relative resources not loaded (more info here).
A workaround is to create an empty empty.html
file, navigate to it and then call page.setContent()
:
// would typically load from a file
const html = '<!DOCTYPE html><title>Hello</title><p>World</p>';
await page.goto('file://empty.html', { waitUntil: 'load' });
await page.setContent(html, { waitUntil: 'networkidle0' });
If you want to load other resources locally which are not available using file://
, you can take advantage of page.setRequestInterception()
:
import path from 'path';
let resources = [
'style.css': {
content: Buffer.from('p {color: navy;}'),
mimetype: 'text/css'
}
]
page.on('request', interceptedRequest => {
const url = new URL(interceptedRequest.url());
if (url.protocol === 'file:' && url.pathname !== 'empty.html') {
const resourceName = path.basename(url.pathname); // Extract the file name
const resource = resources[resourceName];
if (resource) {
interceptedRequest.respond({
status: 200,
contentType: resource.mimetype,
body: resource.content,
});
} else {
interceptedRequest.abort();
}
} else {
interceptedRequest.continue();
}
});
await page.goto(`file:${path.join(__dirname, 'test.html')}`);
– Thole