Trying to render a react component with chrome puppeteer running on my Node.js environment I’m having following problem:
- logging
element
gives me in the headless chrome console:console.log(element)
=><div id="test-wrapper"></div>
testWrapper
in the terminalconsole.log(testWrapper)
=>{}
puppeteer.launch().then(async browser => { const page = await browser.newPage(); const testDocumentPath = path.resolve('./lib/components/util/testDocument.html'); await page.goto(`file://${testDocumentPath}`); const testWrapper = await page.evaluate((selector) => { const element = document.querySelector(selector); console.log(element); return element; }, '#test-wrapper'); console.log(testWrapper); });
So trying to do …
ReactDOM.render(
<div>{':)'}</div>,
testWrapper
);
… obviously results in an error (node:90555) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Invariant Violation: _registerComponent(...): Target container is not a DOM element.
I feel like even if I manage to get the DOM element I’m missing something here to inject a react application.
.evaluate
does not return a dom element. And, you are trying to modify the elements in different context. The page in the browser window and the context you have in your nodeJS is absolutely different.Here is a different way to deal with React and Puppeteer. First, I have an entry file where I export the function to window.
By doing this, I can access it from the browsers context easily. Instead of window, you can actually export it and try expose-loader and so on. I'll use webpack to build it.
On the webpack config,
Now whenever I run webpack, it'll create a bundle.js file for me. Now let's have a puppeteer file,
As you can see, I'm using the renderIt function that I exposed to window earlier. And when I run it, here is the result,
Sweet! Hello from react :)
Oh! And if it fails to execute script on the page due to CORS issue, you can inject it instead using the old injectFile function, until they fix their addScriptTag function, or remove deprecation from injectFile.