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 Node.js. We recommend that you use the latest LTS 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.

    Create your application

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

    ```sh npm2yarn mkdir my-electron-app && cd my-electron-app npm init

    1. The interactive `init` command will prompt you to set some fields in your config.
    2. There are a few rules to follow for the purposes of this tutorial:
    3. * `entry point` should be `main.js`.
    4. * `author` and `description` can be any value, but are necessary for
    5. [app packaging](#package-and-distribute-your-application).
    6. Your `package.json` file should look something like this:
    7. ```json
    8. {
    9. "name": "my-electron-app",
    10. "version": "1.0.0",
    11. "description": "Hello World!",
    12. "main": "main.js",
    13. "author": "Jane Doe",
    14. "license": "MIT"
    15. }

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

    ```sh npm2yarn $ npm install —save-dev electron

    1. > Note: If you're encountering any issues with installing Electron, please
    2. > refer to the [Advanced Installation][advanced-installation] guide.
    3. Finally, you want to be able to execute Electron. In the [`scripts`][package-scripts]
    4. field of your `package.json` config, add a `start` command like so:
    5. ```json
    6. {
    7. "scripts": {
    8. "start": "electron ."
    9. }
    10. }

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

    ```sh npm2yarn npm start

    1. > Note: This script tells Electron to run on your project's root folder. At this stage,
    2. > your app will immediately throw an error telling you that it cannot find an app to run.
    3. [advanced-installation]: ./installation.md
    4. [package-scripts]: https://docs.npmjs.com/cli/v7/using-npm/scripts
    5. ### Run the main process
    6. The entry point of any Electron application is its `main` script. This script controls the
    7. **main process**, which runs in a full Node.js environment and is responsible for
    8. controlling your app's lifecycle, displaying native interfaces, performing privileged
    9. operations, and managing renderer processes (more on that later).
    10. During execution, Electron will look for this script in the [`main`][package-json-main]
    11. field of the app's `package.json` config, which you should have configured during the
    12. [app scaffolding](#scaffold-the-project) step.
    13. To initialize the `main` script, create an empty file named `main.js` in the root folder
    14. of your project.
    15. > Note: If you run the `start` script again at this point, your app will no longer throw
    16. > any errors! However, it won't do anything yet because we haven't added any code into
    17. > `main.js`.
    18. [package-json-main]: https://docs.npmjs.com/cli/v7/configuring-npm/package-json#main
    19. ### Create a web page
    20. Before we can create a window for our application, we need to create the content that
    21. will be loaded into it. In Electron, each window displays web contents that can be loaded
    22. from either a local HTML file or a remote URL.
    23. For this tutorial, you will be doing the former. Create an `index.html` file in the root
    24. folder of your project:
    25. ```html
    26. <!DOCTYPE html>
    27. <html>
    28. <head>
    29. <meta charset="UTF-8">
    30. <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
    31. <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    32. <meta http-equiv="X-Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    33. </head>
    34. <body>
    35. <h1>Hello World!</h1>
    36. We are using Node.js <span id="node-version"></span>,
    37. Chromium <span id="chrome-version"></span>,
    38. and Electron <span id="electron-version"></span>.
    39. </body>
    40. </html>

    Note: Looking at this HTML document, you can observe that the version numbers are missing from the body text. We’ll manually insert them later using JavaScript.

    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 module, which controls your application’s event lifecycle.
    • The BrowserWindow module, which creates and manages application windows.

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

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

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

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

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

    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. })

    Note: At this point, your window controls should be fully functional!

    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.

    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 dependency of ['chrome', 'node', 'electron']) {
    7. replaceText(`${dependency}-version`, process.versions[dependency])
    8. }
    9. })

    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.

    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 to bundle and minify your code or React 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. // main.js
    2. // Modules to control application life and create native browser window
    3. const { app, BrowserWindow } = require('electron')
    4. const path = require('path')
    5. const createWindow = () => {
    6. // Create the browser window.
    7. width: 800,
    8. height: 600,
    9. webPreferences: {
    10. preload: path.join(__dirname, 'preload.js')
    11. }
    12. })
    13. // and load the index.html of the app.
    14. // Open the DevTools.
    15. // mainWindow.webContents.openDevTools()
    16. }
    17. // This method will be called when Electron has finished
    18. // initialization and is ready to create browser windows.
    19. // Some APIs can only be used after this event occurs.
    20. app.whenReady().then(() => {
    21. createWindow()
    22. app.on('activate', () => {
    23. // On macOS it's common to re-create a window in the app when the
    24. // dock icon is clicked and there are no other windows open.
    25. if (BrowserWindow.getAllWindows().length === 0) createWindow()
    26. })
    27. })
    28. // Quit when all windows are closed, except on macOS. There, it's common
    29. // for applications and their menu bar to stay active until the user quits
    30. // explicitly with Cmd + Q.
    31. app.on('window-all-closed', () => {
    32. if (process.platform !== 'darwin') app.quit()
    33. })
    34. // In this file you can include the rest of your app's specific main process
    35. // code. You can also put them in separate files and require them here.
    1. // preload.js
    2. // All of 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. <meta http-equiv="X-Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    9. <title>Hello World!</title>
    10. </head>
    11. <body>
    12. <h1>Hello World!</h1>
    13. We are using Node.js <span id="node-version"></span>,
    14. Chromium <span id="chrome-version"></span>,
    15. and Electron <span id="electron-version"></span>.
    16. <!-- You can also require other files to run in this process -->
    17. <script src="./renderer.js"></script>
    18. </body>
    19. </html>

    ```fiddle docs/fiddles/quick-start

    1. Create a distributable using Forge’s make command:

      ```sh npm2yarn npm run make

      my-electron-app@1.0.0 make /my-electron-app electron-forge make

      ✔ Checking your system ✔ Resolving Forge Config We need to package your application before we can make it ✔ Preparing to Package Application for arch: x64 ✔ Preparing native dependencies ✔ Packaging Application Making for the following targets: zip ✔ Making for target: zip - On platform: darwin - For arch: x64

      1. Electron Forge creates the `out` folder where your package will be located:
      2. ```plain
      3. // Example for macOS
      4. out/
      5. ├── out/make/zip/darwin/x64/my-electron-app-darwin-x64-1.0.0.zip