Quick Start

    By the end of this tutorial, your app will open a browser window that displays a web page with information about which Chromium, Node.js, and Electron versions are running.

    To use Electron, you need to install . We recommend that you use the latest version available.

    To check that Node.js was installed correctly, type the following commands in your terminal client:

    The commands should print the versions of Node.js and npm accordingly.

    Note: Since Electron embeds Node.js into its binary, the version of Node.js running your code is unrelated to the version running on your system.

    Electron apps follow the same general structure as other Node.js projects. Start by creating a folder and initializing an npm package.

    • npm
    • Yarn
    1. mkdir my-electron-app && cd my-electron-app
    2. npm init
    1. mkdir my-electron-app && cd my-electron-app
    2. yarn init

    The interactive init command will prompt you to set some fields in your config. There are a few rules to follow for the purposes of this tutorial:

    • entry point should be main.js.
    • author and description can be any value, but are necessary for app packaging.

    Your package.json file should look something like this:

    1. {
    2. "name": "my-electron-app",
    3. "version": "1.0.0",
    4. "description": "Hello World!",
    5. "main": "main.js",
    6. "author": "Jane Doe",
    7. "license": "MIT"
    8. }

    Then, install the electron package into your app’s devDependencies.

    • npm
    • Yarn
    1. npm install --save-dev electron
    1. yarn add --dev electron

    Note: If you’re encountering any issues with installing Electron, please refer to the guide.

    Finally, you want to be able to execute Electron. In the scripts field of your package.json config, add a start command like so:

    1. {
    2. "scripts": {
    3. "start": "electron ."
    4. }
    5. }

    This start command will let you open your app in development mode.

    • npm
    • Yarn
    1. npm start
    1. yarn start
    2. # couldn't auto-convert command

    Run the main process

    The entry point of any Electron application is its main script. This script controls the main process, which runs in a full Node.js environment and is responsible for controlling your app’s lifecycle, displaying native interfaces, performing privileged operations, and managing renderer processes (more on that later).

    During execution, Electron will look for this script in the main field of the app’s package.json config, which you should have configured during the step.

    To initialize the main script, create an empty file named main.js in the root folder of your project.

    Note: If you run the start script again at this point, your app will no longer throw any errors! However, it won’t do anything yet because we haven’t added any code into main.js.

    For this tutorial, you will be doing the former. Create an index.html file in the root folder of your project:

    Opening your web page in a browser window

    Now that you have a web page, load it into an application window. To do so, you’ll need two Electron modules:

    • The app module, which controls your application’s event lifecycle.
    • The module, which creates and manages application windows.

    Because the main process runs Node.js, you can import these as CommonJS modules at the top of your file:

    1. const { app, BrowserWindow } = require('electron')

    Then, add a createWindow() function that loads index.html into a new BrowserWindow instance.

    1. const createWindow = () => {
    2. const win = new BrowserWindow({
    3. width: 800,
    4. height: 600
    5. })
    6. win.loadFile('index.html')
    7. }

    Next, call this createWindow() function to open your window.

    In Electron, browser windows can only be created after the app module’s event is fired. You can wait for this event by using the app.whenReady() API. Call createWindow() after whenReady() resolves its Promise.

    1. app.whenReady().then(() => {
    2. createWindow()
    3. })

    Note: At this point, your Electron application should successfully open a window that displays your web page!

    Although you can now open a browser window, you’ll need some additional boilerplate code to make it feel more native to each platform. Application windows behave differently on each OS, and Electron puts the responsibility on developers to implement these conventions in their app.

    In general, you can use the process global’s platform attribute to run code specifically for certain operating systems.

    Quit the app when all windows are closed (Windows & Linux)

    On Windows and Linux, exiting all windows generally quits an application entirely.

    To implement this, listen for the app module’s ‘window-all-closed’ event, and call if the user is not on macOS (darwin).

    1. app.on('window-all-closed', () => {
    2. if (process.platform !== 'darwin') app.quit()
    3. })

    Open a window if none are open (macOS)

    Whereas Linux and Windows apps quit when they have no windows open, macOS apps generally continue running even without any windows open, and activating the app when no windows are available should open a new one.

    To implement this feature, listen for the app module’s event, and call your existing createWindow() method if no browser windows are open.

    Because windows cannot be created before the ready event, you should only listen for activate events after your app is initialized. Do this by attaching your event listener from within your existing whenReady() callback.

    1. app.whenReady().then(() => {
    2. createWindow()
    3. app.on('activate', () => {
    4. if (BrowserWindow.getAllWindows().length === 0) createWindow()
    5. })
    6. })

    Access Node.js from the renderer with a preload script

    Now, the last thing to do is print out the version numbers for Electron and its dependencies onto your web page.

    Accessing this information is trivial to do in the main process through Node’s global process object. However, you can’t just edit the DOM from the main process because it has no access to the renderer’s document context. They’re in entirely different processes!

    This is where attaching a preload script to your renderer comes in handy. A preload script runs before the renderer process is loaded, and has access to both renderer globals (e.g. window and document) and a Node.js environment.

    Create a new script named preload.js as such:

    1. window.addEventListener('DOMContentLoaded', () => {
    2. const replaceText = (selector, text) => {
    3. const element = document.getElementById(selector)
    4. }
    5. for (const dependency of ['chrome', 'node', 'electron']) {
    6. replaceText(`${dependency}-version`, process.versions[dependency])
    7. }
    8. })

    The above code accesses the Node.js process.versions object and runs a basic replaceText helper function to insert the version numbers into the HTML document.

    To attach this script to your renderer process, pass in the path to your preload script to the webPreferences.preload option in your existing BrowserWindow constructor.

    1. // include the Node.js 'path' module at the top of your file
    2. const path = require('path')
    3. const createWindow = () => {
    4. const win = new BrowserWindow({
    5. width: 800,
    6. height: 600,
    7. webPreferences: {
    8. preload: path.join(__dirname, 'preload.js')
    9. }
    10. })
    11. win.loadFile('index.html')
    12. }
    13. // ...

    There are two Node.js concepts that are used here:

    • The string points to the path of the currently executing script (in this case, your project’s root folder).
    • The path.join API joins multiple path segments together, creating a combined path string that works across all platforms.

    We use a path relative to the currently executing JavaScript file so that your relative path will work in both development and packaged mode.

    At this point, you might be wondering how to add more functionality to your application.

    For any interactions with your web contents, you want to add scripts to your renderer process. Because the renderer runs in a normal web environment, you can add a <script> tag right before your index.html file’s closing </body> tag to include any arbitrary scripts you want:

    1. <script src="./renderer.js"></script>

    The code contained in renderer.js can then use the same JavaScript APIs and tooling you use for typical front-end development, such as using webpack to bundle and minify your code or to manage your user interfaces.

    Recap

    After following the above steps, you should have a fully functional Electron application that looks like this:

    The full code is available below:

    1. // preload.js
    2. // All the Node.js APIs are available in the preload process.
    3. // It has the same sandbox as a Chrome extension.
    4. window.addEventListener('DOMContentLoaded', () => {
    5. const replaceText = (selector, text) => {
    6. const element = document.getElementById(selector)
    7. if (element) element.innerText = text
    8. }
    9. for (const dependency of ['chrome', 'node', 'electron']) {
    10. replaceText(`${dependency}-version`, process.versions[dependency])
    11. }
    12. })
    1. <!--index.html-->
    2. <!DOCTYPE html>
    3. <html>
    4. <head>
    5. <meta charset="UTF-8">
    6. <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
    7. <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    8. <title>Hello World!</title>
    9. </head>
    10. <body>
    11. <h1>Hello World!</h1>
    12. We are using Node.js <span id="node-version"></span>,
    13. Chromium <span id="chrome-version"></span>,
    14. and Electron <span id="electron-version"></span>.
    15. <!-- You can also require other files to run in this process -->
    16. <script src="./renderer.js"></script>
    17. </body>
    18. </html>

    Open in Fiddle

    • main.js
    • preload.js
    • index.html
    1. const { app, BrowserWindow } = require('electron')
    2. const path = require('path')
    3. function createWindow () {
    4. const win = new BrowserWindow({
    5. width: 800,
    6. height: 600,
    7. webPreferences: {
    8. preload: path.join(__dirname, 'preload.js')
    9. }
    10. })
    11. win.loadFile('index.html')
    12. }
    13. app.whenReady().then(() => {
    14. createWindow()
    15. app.on('activate', () => {
    16. if (BrowserWindow.getAllWindows().length === 0) {
    17. }
    18. })
    19. })
    20. app.on('window-all-closed', () => {
    21. if (process.platform !== 'darwin') {
    22. app.quit()
    23. })
    1. window.addEventListener('DOMContentLoaded', () => {
    2. const replaceText = (selector, text) => {
    3. const element = document.getElementById(selector)
    4. if (element) element.innerText = text
    5. }
    6. for (const type of ['chrome', 'node', 'electron']) {
    7. replaceText(`${type}-version`, process.versions[type])
    8. }
    9. })
    1. <!DOCTYPE html>
    2. <html>
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>Hello World!</title>
    6. <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
    7. </head>
    8. <body>
    9. <h1>Hello World!</h1>
    10. <p>
    11. We are using Node.js <span id="node-version"></span>,
    12. Chromium <span id="chrome-version"></span>,
    13. and Electron <span id="electron-version"></span>.
    14. </p>
    15. </body>
    16. </html>

    To summarize all the steps we’ve done:

    • We bootstrapped a Node.js application and added Electron as a dependency.
    • We created a main.js script that runs our main process, which controls our app and runs in a Node.js environment. In this script, we used Electron’s app and BrowserWindow modules to create a browser window that displays web content in a separate process (the renderer).
    • In order to access certain Node.js functionality in the renderer, we attached a preload script to our BrowserWindow constructor.

    The fastest way to distribute your newly created app is using Electron Forge.

    1. Add Electron Forge as a development dependency of your app, and use its import command to set up Forge’s scaffolding:

      • npm
      • Yarn
      1. npm install --save-dev @electron-forge/cli
      2. npx electron-forge import
      3. Checking your system
      4. Initializing Git Repository
      5. Writing modified package.json file
      6. Installing dependencies
      7. Writing modified package.json file
      8. Fixing .gitignore
      9. We have ATTEMPTED to convert your app to be in a format that electron-forge understands.
      10. Thanks for using "electron-forge"!!!
      1. yarn add --dev @electron-forge/cli
      2. npx electron-forge import
      3. Checking your system
      4. Initializing Git Repository
      5. Writing modified package.json file
      6. Installing dependencies
      7. Writing modified package.json file
      8. Fixing .gitignore
      9. We have ATTEMPTED to convert your app to be in a format that electron-forge understands.
      10. Thanks for using "electron-forge"!!!
    2. Create a distributable using Forge’s make command:

      • npm
      • Yarn
      1. npm run make
      2. > my-electron-app@1.0.0 make /my-electron-app
      3. > electron-forge make
      4. Checking your system
      5. Resolving Forge Config
      6. We need to package your application before we can make it
      7. Preparing to Package Application for arch: x64
      8. Preparing native dependencies
      9. Packaging Application
      10. Making for the following targets: zip
      11. Making for target: zip - On platform: darwin - For arch: x64

      Electron Forge creates the out folder where your package will be located:

      1. // Example for macOS
      2. out/
      3. ├── out/make/zip/darwin/x64/my-electron-app-darwin-x64-1.0.0.zip
      4. ├── ...