Open In App

How to take Screenshots in ElectronJS ?

ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime.

Electron supports Generating PDF files and Printing files from within the webpage in desktop applications. Along with these features, Electron also provides a way by which we can take screenshots of the webpage and save it as an image file onto the native System using the Instance methods of the BrowserWindow Object and the webContents property. Electron internally handles images using the NativeImage class, hence we also require the Instance methods of the nativeImage module to convert the respective NativeImage into PNG or JPEG format before they can be saved onto the native System. For Saving the files onto the native system we will use the Instance methods of the dialog module in Electron. This tutorial will demonstrate how to take Screenshots of the webpage in Electron and save them onto the native System.



We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system.

Example: Follow the Steps given in Generate PDF in ElectronJS to set up the basic Electron Application. Copy the Boilerplate code for the main.js file and the index.html file as provided in the article. Also, perform the necessary changes mentioned for the package.json file to launch the Electron Application. We will continue building our application using the same code base. The basic steps required to set up the Electron application remain the same. 
 package.json: 



{
  "name": "electron-screenshot",
  "version": "1.0.0",
  "description": "Screenshot in Electron",
  "main": "main.js",
  "scripts": {
    "start": "electron ."
  },
  "keywords": [
    "electron"
  ],
  "author": "Radhesh Khanna",
  "license": "ISC",
  "dependencies": {
    "electron": "^8.3.0"
  }
}

Create the assets folder according to the project structure. We will be using the assets folder as the default path to store the screenshot images taken by the application. 

Output: At this point, our basic Electron Application is set up. Upon launching the application, we should see the following result. 

Screenshot in Electron: The BrowserWindow Instance, webContents Property and the dialog module are part of the Main Process. To import and use the BrowserWindow object and dialog module in the Renderer Process, we will be using Electron remote module. 

index.html: Add the following snippet in that file. The Take Screenshot button does not have any functionality associated with it yet. To change this, add the following code in the index.js file.




<h3>Screenshot of Page in Electron</h3>
<button id="screenshot">
      Take Screenshot
</button>

index.js: Add the following snippet in that file. 




const electron = require("electron");
const BrowserWindow = electron.remote.BrowserWindow;
const path = require("path");
const fs = require("fs");
 
// Importing dialog module using remote
const dialog = electron.remote.dialog;
 
// let win = BrowserWindow.getAllWindows()[0];
let win = BrowserWindow.getFocusedWindow();
 
let screenshot = document.getElementById("screenshot");
screenshot.addEventListener("click", (event) => {
    win.webContents
        .capturePage({
            x: 0,
            y: 0,
            width: 800,
            height: 600,
        })
        .then((img) => {
            dialog
                .showSaveDialog({
                    title: "Select the File Path to save",
 
                    // Default path to assets folder
                    defaultPath: path.join(__dirname,
                        "../assets/image.png"),
 
                    // defaultPath: path.join(__dirname,
                    // '../assets/image.jpeg'),
                    buttonLabel: "Save",
 
                    // Restricting the user to only Image Files.
                    filters: [
                        {
                            name: "Image Files",
                            extensions: ["png", "jpeg", "jpg"],
                        },
                    ],
                    properties: [],
                })
                .then((file) => {
                    // Stating whether dialog operation was
                    // cancelled or not.
                    console.log(file.canceled);
                    if (!file.canceled) {
                        console.log(file.filePath.toString());
 
                        // Creating and Writing to the image.png file
                        // Can save the File as a jpeg file as well,
                        // by simply using img.toJPEG(100);
                        fs.writeFile(file.filePath.toString(),
                            img.toPNG(), "base64", function (err) {
                                if (err) throw err;
                                console.log("Saved!");
                            });
                    }
                })
                .catch((err) => {
                    console.log(err);
                });
        })
        .catch((err) => {
            console.log(err);
        });
});

Explanation: The win.webContents.capturePage(rectangle) Instance method simply captures the screenshot of the webpage specified by the rectangle object. Omitting the rectangle object will capture the whole visible webpage i.e. the entire visible BrowserWindow Instance. It takes in the following parameters. 

The win.webContents.capturePage() Instance method returns a Promise and it resolves with a NativeImage instance on successful Screenshot capture. We need to convert this NativeImage Instance to either JPEG or PNG using the Instance methods of the nativeImage module before it can be saved on the native System. 

The dialog.showSaveDialog(options) Instance method of the dialog module is used to interact with the native File System to open a System dialog for saving files locally by fetching the file path as specified by the user. By default, we are specifying the file path to the assets folder and save the image file in PNG format with the name image.png. For more information on how to restrict the user to PNG/JPEG formats and properties of the dialog.showSaveDialog() method, Refer to Save Files in ElectronJS.
To get the current BrowserWindow Instance in the Renderer Process, we can use some of the Static Methods provided by the BrowserWindow object. 

Output:


Article Tags :