Open In App

How to take Screenshots in ElectronJS ?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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.

html




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


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

javascript




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. 

  • rectangle: Object (Optional) The rectangle object. It consists of the following parameters which are required to define a rectangle and its position on the webpage/screen. 
    • x: Integer The X coordinate of the origin of the rectangle. In this case, the X coordinate represents the coordinate of the webpage/screen to be captured.
    • y: Integer The Y coordinate of the origin of the rectangle. In this case, the Y coordinate represents the coordinate of the webpage/screen to be captured.
    • width: Integer The width of the rectangle. In this case, it represents the width of the webpage/screen to be captured.
    • height: Integer The height of the rectangle. In this case, it represents the height of the webpage/screen to be captured.

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. 

  • image.toPNG(options) This Instance method converts the NativeImage Instance to PNG format by returning a NodeJS Buffer that contains the image’s PNG encoded data. We will use the Buffer returned by this method to write the image to a .png file as shown in the code using the fs module. The default Encoding of the PNG file will be base64. It takes in the following parameters. 
    • options: Object (Optional) The options object consists of a single parameter i.e. the scaleFactor: Double (Optional) representing the scale factor (zoom) of the Image. By default, the value taken is 1.0.
  • image.toJPEG(quality) This Instance method converts the NativeImage Instance to JPEG format by returning a NodeJS BUffer that contains the image’s JPEG encoded data. We will use the Buffer returned by this method to write the image to a .jpeg file as shown in the code using the fs module. The default Encoding of the JPEG file will be base64. It takes in the following parameters.
    • quality: Integer This value cannot be empty. It can take in a value between 0 and 100. This value represents the quality factor of the image, 0 being the lowest quality and 100 being the highest quality image.

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. 

  • BrowserWindow.getAllWindows(): This method returns an Array of active/opened BrowserWindow Instances. In this application, we have only one active BrowserWindow Instance and it can be directly referred from the Array as shown in the code.
  • BrowserWindow.getFocusedWindow(): This method returns the BrowserWindow Instance which is focused in the Application. If no current BrowserWindow Instance is found, it returns null. In this application, we only have one active BrowserWindow Instance and it can be directly referred to using this method as shown in the code. 

Output:



Last Updated : 04 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads