Puppeteer is a powerful tool for automating browsers, but did you know it can also run within a browser itself? This enables you to leverage Puppeteer’s capabilities for tasks that don’t require Node.js specific features.
While running in the browser, Puppeteer offers a variety of functionalities including:
:::note
See https://github.com/puppeteer/puppeteer/tree/main/examples/puppeteer-in-browser for a complete example.
:::
To run Puppeteer in the browser, first you need to produce a browser-compatible build using a bundler such as rollup or webpack:
puppeteer-core/lib/esm/puppeteer/puppeteer-core-browser.js'
:import puppeteer from 'puppeteer-core/lib/esm/puppeteer/puppeteer-core-browser.js';
const browser = await puppeteer.connect({
browserWSEndpoint: wsUrl,
});
alert('Browser has ' + (await browser.pages()).length + ' pages');
browser.disconnect();
import {nodeResolve} from '@rollup/plugin-node-resolve';
export default {
input: 'main.mjs',
output: {
format: 'esm',
dir: 'out',
},
// If you do not need to use WebDriver BiDi protocol,
// exclude chromium-bidi/lib/cjs/bidiMapper/BidiMapper.js to minimize the bundle size.
external: ['chromium-bidi/lib/cjs/bidiMapper/BidiMapper.js'],
plugins: [
nodeResolve({
// Indicate that we target a browser environment.
browser: true,
// Exclude any dependencies except for puppeteer-core.
// `npm install puppeteer-core` # To install puppeteer-core if needed.
resolveOnly: ['puppeteer-core'],
}),
],
};
:::note
Do not forget to include a valid browser WebSocket endpoint when connecting to an instance.
:::