Emulation 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.

In traditional web applications, we have the Toggle View functionality in which we are given the choice of whether we would like to view the Desktop version or the Mobile version of the website. This depends upon the device from which we are currently viewing the website. This is also a part of Emulation. Emulation refers to the ability of software to emulate (or imitate) another program or take on characteristics that are different from the original/intended one. This is done to enhance the user experience or provide developers with the ability to test the application on different platforms/characteristics. Electron provides us with a way by which we can Emulate a Desktop or a Mobile device using the Instance methods and events of the built-in BrowserWindow object and the webContents property. This tutorial will demonstrate how to Emulate a device in Electron.

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.

  • Project Structure:

Project Structure

Example: Follow the Steps given in Dynamic Styling in ElectronJS to setup 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 setup the Electron application remain the same. 



package.json: 

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

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

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

  • index.html: Add the following snippet in that file. The Buttons do not have any functionality associated with them yet. To change this, add the following in the index.js file. 

html

filter_none

edit
close

play_arrow

link
brightness_4
code

<h3>
  Emulation in ElectronJS
</h3>
<button id="emulate">
  Emulate Mobile
</button>
<button id="desktop">
  Emulate Desktop
</button>
<button id="disable">
  Disable Device Emulation
</button>

chevron_right


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

javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

const electron = require("electron");
  
// Importing BrowserWindow from Main 
// Process with Electron remote
const BrowserWindow = electron.remote.BrowserWindow;
let win = BrowserWindow.getFocusedWindow();
// let win = BrowserWindow.getAllWindows()[0];
  
var emulate = document.getElementById("emulate");
emulate.addEventListener("click", () => {
    win.webContents.enableDeviceEmulation({
        screenPosition: "mobile",
        
        // Defined as Size of Galaxy S5 in 
        // Chromium Browser
        screenSize: {
            width: 360,
            height: 640,
        },
        viewPosition: {
            x: 0,
            y: 0,
        },
        // Defined as Size of Galaxy S5 in
        // Chromium Browser
        viewSize: {
            width: 360,
            height: 640,
        },
        deviceScaleFactor: 0,
        scale: 1,
    });
});
  
var desktop = document.getElementById("desktop");
desktop.addEventListener("click", () => {
    win.webContents.enableDeviceEmulation({
        screenPosition: "desktop",
        
        // Same as BrowserWindow Instance 
        // in Main Process
        screenSize: {
            width: 800,
            height: 600,
        },
        viewPosition: {
            x: 0,
            y: 0,
        },
        // Same as BrowserWindow Instance 
        // in Main Process
        viewSize: {
            width: 800,
            height: 600,
        },
        deviceScaleFactor: 0,
        scale: 1,
    });
});
  
var disable = document.getElementById("disable");
disable.addEventListener("click", () => {
    win.webContents.disableDeviceEmulation();
});

chevron_right


A detailed Explanation of all the Instance methods of the webContents property used in the code are given below. 

  • webContents.enableDeviceEmulation(parameters) This Instance method simply enables Device Emulation based on the parameters provided to it. This method does not have a Return type. It takes in the following object. 
    • parameters: Object It takes in the following parameters,
      • screenPosition: String This property specifies the Emulation. It represents the screen view which should be emulated for the application. It can hold either desktop or mobile value. desktop value represents a Desktop Screen Type and mobile value represents a Mobile Screen Type. Default value is desktop. In our code, we have toggled between the two values based on the other properties provided in the parameters object.
      • screenSize: Object (Optional) Set the emulated Screen Size using the Size object. This parameter is important for when the screenPosition property is set to mobile. It takes in the following parameters. 
        • width: Integer The width of the Screen Size.
        • height: Integer The height of the Screen Size.
      • viewSize: Object (Optional) Set the emulated View Size using the Size object. This parameter is important for when the screenPosition property is set to mobile. It takes in the following parameters.  Default is an empty object. Empty object means No Override.
        • width: Integer The width of the View Size.
        • height: Integer The height of the View Size.
      • viewPosition: Object This parameter is used to Position the View Frame on the Screen using the Point Object. This parameter is important for when the screenPosition property is set to mobile. It takes in the following parameters.
        • x: Integer The X-coordinate of the Position.
        • y: Integer The Y-coordinate of the Position.
      • deviceScaleFactor: Integer This parameter sets the device Scale Factor. Default value is 0.
      • scale: Float This parameter defines the Scale (Zoom) of the Emulated View as defined by the screenPosition property inside the available space. This value overrides the fit-to-view mode. Default value is 1.
  • webContents.disableDeviceEmulation() This Instance method simply disables the device emulation enabled by webContents.enableDeviceEmulation() method. This method does not take in any parameters and does not have Return Type.

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 refered 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 using this method as shown in the code. 
     

Output:

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.