I want to inject some HTML into a specific element on a page using puppeteer.
The HTML must be injected before any JavaScript is executed.
There are two ways I think I could do this:
- Inject HTML using
page.evaluateOnNewDocument
This function is "is invoked after the document was created" but I can't access DOM elements from it. eg:
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
page.on('console', consoleObj => console.log(consoleObj.text()));
await page.evaluateOnNewDocument(
() => {
const content = document.querySelector('html');
console.log(content);
}
);
await page.goto(process.argv[2]);
await browser.close();
})();
This script just outputs newlines when I visit a page.
- Using
page.setJavaScriptEnabled
to prevent the javascript from executing before I inject the HTML. As per the docs though, this doesn't start executing the javascript after I turn it back on. eg:
My script looks something like this:
const fs = require('fs');
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
const html = fs.readFileSync('./example.html', 'utf8');
await page.setJavaScriptEnabled(false)
await page.goto(process.argv[2]);
await page.evaluate(
content => {
const pageEl = document.querySelector('div.page');
let node = document.createElement('div');
node.innerHTML = content;
pageEl.appendChild(node);
}, html
);
await page.setJavaScriptEnabled(true)
await browser.close();
})();
Alternatively, it may also be possible to do something like this, though that seems overly complex for what is a fairly simple request.
Is there an easier way to do this that I am overlooking?
Cheers