For a long time, I tried to create a way to do onboarding for members to go through some web page and fill in their details. I searched for many open-source libraries that can do it and found nothing. So I have decided to implement it myself.
For this article, I will use Puppeteer and ReactJS.Puppeteer is a Node.js library that automates several browser actions such as form submission, crawling single-page applications, UI testing, and in particular, generating screenshot and PDF versions of web pages.
We will open a webpage with Puppeteer, send to the client (React) a screenshot of every frame and reflect actions to Puppeteer by clicking on the image. To begin with, let’s set up the project environment.
Just a quick background about us. Novu is the first open-source notification infrastructure. We basically help to manage all the product notifications. It can be In-App (the bell icon like you have in the Dev Community – Websockets), Emails, SMSs and so on.
I would be super happy if you could give us a star! It will help me to make more articles every week 🚀 https://github.com/novuhq/novu
Here, we’ll set up the project environment for the screen-sharing app. You’ll also learn how to add Socket.io to a React and Node.js application and connect both development servers for real-time communication via Socket.io.
Create the project folder containing two sub-folders named client and server.
mkdir screen-sharing-appcd screen-sharing-appmkdir client server
Navigate into the client folder via your terminal and create a new React.js project.
cd clientnpx create-react-app ./
Install Socket.io client API and React Router. React Router is a JavaScript library that enables us to navigate between pages in a React application.
npm install socket.io-client react-router-dom
Delete the redundant files such as the logo and the test files from the React app, and update the App.js file to display Hello World as below.
Navigate into the server folder and create a package.json file.
cd server & npm init -y
Install Express.js, CORS, Nodemon, and Socket.io Server API.
Express.js is a fast, minimalist framework that provides several features for building web applications in Node.js. CORS is a Node.js package that allows communication between different domains.
Nodemon is a Node.js tool that automatically restarts the server after detecting file changes, and Socket.io allows us to configure a real-time connection on the server.
npm install express cors nodemon socket.io
Create an index.js file – the entry point to the web server.
touch index.js
Set up a simple Node.js server using Express.js. The code snippet below returns a JSON object when you visit the http://localhost:4000/api in your browser.
Next, add Socket.io to the project to create a real-time connection. Before the app.get() block, copy the code below. Next, add Socket.io to the project to create a real-time connection. Before the app.get() block, copy the code below.
//New imports.....const socketIO = require('socket.io')(http, { cors: { origin: "http://localhost:3000" }});//Add this before the app.get() blocksocketIO.on('connection', (socket) => { console.log(`\u26a1: ${socket.id} user just connected!`); socket.on('disconnect', () => { console.log('\ud83d\udd25: A user disconnected'); });});
From the code snippet above, the socket.io("connection") function establishes a connection with the React app, then creates a unique ID for each socket and logs the ID to the console whenever a user visits the web page.
When you refresh or close the web page, the socket fires the disconnect event showing that a user has disconnected from the socket.
Configure Nodemon by adding the start command to the list of scripts in the package.json file. The code snippet below starts the server using Nodemon.
//In server/package.json"scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "nodemon index.js" },
You can now run the server with Nodemon by using the command below.
In this section, you’ll learn how to take automatic screenshots of web pages using Puppeteer and the Chrome DevTools Protocol. Unlike the regular screenshot function provided by Puppeteer, Chrome’s API creates very fast screenshots that won’t slow down Puppeteer and your runtime because it is asynchronous.
Navigate into the server folder and install Puppeteer.
cd servernpm install puppeteer
Update the Modal.js file to send the URL for the web page provided by the user to the Node.js server.
Create a listener for the browse event on the backend server.
socketIO.on("connection", (socket) => { console.log(`\u26a1: ${socket.id} user just connected!`); socket.on("browse", async ({ url }) => { console.log("Here is the URL >>>> ", url); }); socket.on("disconnect", () => { socket.disconnect(); console.log("\ud83d\udd25: A user disconnected"); });});
Since we’ve been able to collect the URL from the React app, let’s create screenshots using Puppeteer and Chrome DevTools Protocol.
Create a screen.shooter.js file and copy the code below:
const { join } = require("path");const fs = require("fs").promises;const emptyFunction = async () => {};const defaultAfterWritingNewFile = async (filename) => console.log(`${filename} was written`);class PuppeteerMassScreenshots { /* page - represents the web page socket - Socket.io options - Chrome DevTools configurations */ async init(page, socket, options = {}) { const runOptions = { //\ud83d\udc47\ud83c\udffb Their values must be asynchronous codes beforeWritingImageFile: emptyFunction, afterWritingImageFile: defaultAfterWritingNewFile, beforeAck: emptyFunction, afterAck: emptyFunction, ...options, }; this.socket = socket; this.page = page; //\ud83d\udc47\ud83c\udffb CDPSession instance is used to talk raw Chrome Devtools Protocol this.client = await this.page.target().createCDPSession(); this.canScreenshot = true; //\ud83d\udc47\ud83c\udffb The frameObject parameter contains the compressed image data // requested by the Page.startScreencast. this.client.on("Page.screencastFrame", async (frameObject) => { if (this.canScreenshot) { await runOptions.beforeWritingImageFile(); const filename = await this.writeImageFilename(frameObject.data); await runOptions.afterWritingImageFile(filename); try { await runOptions.beforeAck(); /*\ud83d\udc47\ud83c\udffb acknowledges that a screencast frame (image) has been received by the frontend. The sessionId - represents the frame number */ await this.client.send("Page.screencastFrameAck", { sessionId: frameObject.sessionId, }); await runOptions.afterAck(); } catch (e) { this.canScreenshot = false; } } }); } async writeImageFilename(data) { const fullHeight = await this.page.evaluate(() => { return Math.max( document.body.scrollHeight, document.documentElement.scrollHeight, document.body.offsetHeight, document.documentElement.offsetHeight, document.body.clientHeight, document.documentElement.clientHeight ); }); //Sends an event containing the image and its full height return this.socket.emit("image", { img: data, fullHeight }); } /* The startOptions specify the properties of the screencast \ud83d\udc49\ud83c\udffb format - the file type (Allowed fomats: 'jpeg' or 'png') \ud83d\udc49\ud83c\udffb quality - sets the image quality (default is 100) \ud83d\udc49\ud83c\udffb everyNthFrame - specifies the number of frames to ignore before taking the next screenshots. (The more frames we ignore, the less screenshots we will have) */ async start(options = {}) { const startOptions = { format: "jpeg", quality: 10, everyNthFrame: 1, ...options, }; try { await this.client?.send("Page.startScreencast", startOptions); } catch (err) {} } /* Learn more here \ud83d\udc47\ud83c\udffb: https://github.com/shaynet10/puppeteer-mass-screenshots/blob/main/index.js */ async stop() { try { await this.client?.send("Page.stopScreencast"); } catch (err) {} }}module.exports = PuppeteerMassScreenshots;
From the code snippet above:
The runOptions object contains four values. beforeWritingImageFile and afterWritingImageFile must contain asynchronous functions that run before and after sending the images to the client.
beforeAck and afterAck represent the acknowledgment sent to the browser as asynchronous code showing that images were received.
The writeImageFilename function calculates the full height of the screencast and sends it together with the screencast image to the React app.
Create an instance of the PuppeteerMassScreenshots and update the server/index.js file to take the screenshots.
//\ud83d\udc47\ud83c\udffb Add the following importsconst puppeteer = require("puppeteer");const PuppeteerMassScreenshots = require("./screen.shooter");socketIO.on("connection", (socket) => { console.log(`\u26a1: ${socket.id} user just connected!`); socket.on("browse", async ({ url }) => { const browser = await puppeteer.launch({ headless: true, }); //\ud83d\udc47\ud83c\udffb creates an incognito browser context const context = await browser.createIncognitoBrowserContext(); //\ud83d\udc47\ud83c\udffb creates a new page in a pristine context. const page = await context.newPage(); await page.setViewport({ width: 1255, height: 800, }); //\ud83d\udc47\ud83c\udffb Fetches the web page await page.goto(url); //\ud83d\udc47\ud83c\udffb Instance of PuppeteerMassScreenshots takes the screenshots const screenshots = new PuppeteerMassScreenshots(); await screenshots.init(page, socket); await screenshots.start(); }); socket.on("disconnect", () => { socket.disconnect(); console.log("\ud83d\udd25: A user disconnected"); });});
Update the Modal.js file to listen for the screencast images from the server.
import { useState, useEffect } from "react";import socketIO from "socket.io-client";const socket = socketIO.connect("http://localhost:4000");const Modal = ({ url }) => { const [image, setImage] = useState(""); const [fullHeight, setFullHeight] = useState(""); useEffect(() => { socket.emit("browse", { url, }); /* \ud83d\udc47\ud83c\udffb Listens for the images and full height from the PuppeteerMassScreenshots. The image is also converted to a readable file. */ socket.on("image", ({ img, fullHeight }) => { setImage("data:image/jpeg;base64," + img); setFullHeight(fullHeight); }); }, [url]); return ( {image && } </div> </div> );};export default Modal;
Congratulations!💃🏻 We’ve been able to display the screenshots in the React app. In the following section, I’ll guide you on making the screencast images interactive.
Here, you’ll learn how to make the screencasts fully interactive such that it behaves like a browser window and responds to the mouse scroll and move events.
[event.currentTarget.getBoundingClient()](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect) returns an object containing information about the size and position of the screencasts relative to the viewport.
event.pageX – returns the position of the mouse pointer; relative to the left edge of the document.
Then, calculate the cursor’s position and send it to the backend via the mouseClick and mouseMove events.
Create a listener to both events on the backend.
socket.on("browse", async ({ url }) => { const browser = await puppeteer.launch({ headless: true, }); const context = await browser.createIncognitoBrowserContext(); const page = await context.newPage(); await page.setViewport({ width: 1255, height: 800, }); await page.goto(url); const screenshots = new PuppeteerMassScreenshots(); await screenshots.init(page, socket); await screenshots.start(); socket.on("mouseMove", async ({ x, y }) => { try { //sets the cursor the position with Puppeteer await page.mouse.move(x, y); /* \ud83d\udc47\ud83c\udffb This function runs within the page's context, calculates the element position from the view point and returns the CSS style for the element. */ const cur = await page.evaluate( (p) => { const elementFromPoint = document.elementFromPoint(p.x, p.y); return window .getComputedStyle(elementFromPoint, null) .getPropertyValue("cursor"); }, { x, y } ); //\ud83d\udc47\ud83c\udffb sends the CSS styling to the frontend socket.emit("cursor", cur); } catch (err) {} }); //\ud83d\udc47\ud83c\udffb Listens for the exact position the user clicked // and set the move to that position. socket.on("mouseClick", async ({ x, y }) => { try { await page.mouse.click(x, y); } catch (err) {} });});
Listen to the cursor event and add the CSS styles to the screenshot container.
So far, you’ve learned how to set up a real-time connection with React.js and Socket.io, take screenshots of webpages with Puppeteer and Chrome DevTools Protocol, and make them interactive.
This article is a demo of what you can build with Puppeteer. You can also generate PDFs of pages, automate form submission, UI testing, test chrome extensions, and many more. Feel free to explore the documentation.