### Verify Node.js and npm Installation in Shell Source: https://github.com/discord/electron/blob/main/docs/tutorial/quick-start.md These shell commands are used to check the installed versions of Node.js and npm, which are prerequisites for developing with Electron. Successful execution confirms that Node.js and npm are correctly installed and accessible from the command line. ```sh node -v npm -v ``` -------------------------------- ### Initialize Electron Project in Shell Source: https://github.com/discord/electron/blob/main/docs/tutorial/quick-start.md These shell commands create a new directory for the project, initialize a Node.js project with default settings (creating package.json), and install Electron as a development dependency. This sets up the basic project structure and includes the Electron framework. ```sh mkdir my-electron-app && cd my-electron-app npm init -y npm i --save-dev electron ``` -------------------------------- ### Import Electron Forge for Packaging in Shell Source: https://github.com/discord/electron/blob/main/docs/tutorial/quick-start.md This shell command uses npx to execute the Electron Forge CLI and import the current project. Electron Forge helps with packaging and distributing the application by modifying the project's package.json and installing necessary dependencies. ```sh npx @electron-forge/cli import ``` -------------------------------- ### Running Electron Quick Start sh Source: https://github.com/discord/electron/blob/main/README.md Provides a sequence of commands to clone the official Electron Quick Start repository, navigate into its directory, install dependencies, and start the minimal Electron application for a quick demonstration. ```sh git clone https://github.com/electron/electron-quick-start cd electron-quick-start npm install npm start ``` -------------------------------- ### Installing Electron Verbose Output - sh Source: https://github.com/discord/electron/blob/main/docs/tutorial/installation.md Installs Electron using the '--verbose' flag to show detailed output, including download progress. Useful for diagnosing issues or monitoring progress on slow networks. ```sh npm install --verbose electron ``` -------------------------------- ### Installing Node.js Package via npm - Shell Source: https://github.com/discord/electron/blob/main/docs/tutorial/quick-start.md Installs a Node.js package ('aws-sdk') as a project dependency using the npm package manager. The '--save' flag adds it to the project's 'dependencies' in the package.json file, making it available for use within the Electron application. ```shell npm install --save aws-sdk ``` -------------------------------- ### Initial package.json Configuration for Electron Source: https://github.com/discord/electron/blob/main/docs/tutorial/quick-start.md This JSON snippet shows the basic structure of a package.json file for an Electron application. It defines the project name, version, and the main entry point script (main.js), which is required for Electron to know where to start the application. ```json { "name": "my-electron-app", "version": "0.1.0", "main": "main.js" } ``` -------------------------------- ### Add Start Script to package.json for Electron Source: https://github.com/discord/electron/blob/main/docs/tutorial/quick-start.md This JSON snippet modifies the package.json file to include a 'start' script. This script is configured to execute the Electron framework with the current directory (.), telling Electron to look for the main script defined in the 'main' field. This allows running the application using `npm start`. ```json { "name": "my-electron-app", "version": "0.1.0", "main": "main.js", "scripts": { "start": "electron ." } } ``` -------------------------------- ### Installing Electron Globally - npm Source: https://github.com/discord/electron/blob/main/docs/tutorial/installation.md This command installs the 'electron' command globally on your system, allowing you to run Electron applications or use the Electron CLI from any directory. Requires appropriate permissions. ```sh npm install electron -g ``` -------------------------------- ### Run Electron Application in Shell Source: https://github.com/discord/electron/blob/main/docs/tutorial/quick-start.md This shell command executes the 'start' script defined in the project's package.json file. As configured in the previous step, this command launches the Electron application using the specified main script. ```sh npm start ``` -------------------------------- ### Cloning Electron Quick Start and Opening in VSCode (Shell) Source: https://github.com/discord/electron/blob/main/docs/tutorial/debugging-vscode.md Provides the shell commands to clone the official Electron Quick Start repository from GitHub and then open the resulting directory in Visual Studio Code. This is the initial step to prepare a project environment for debugging. ```sh $ git clone git@github.com:electron/electron-quick-start.git $ code electron-quick-start ``` -------------------------------- ### Installing electron-windows-store CLI - sh Source: https://github.com/discord/electron/blob/main/docs/tutorial/windows-store-guide.md Installs the `electron-windows-store` command-line interface tool globally using npm, which is required to convert Electron applications to Windows Store (.appx) packages. This tool facilitates the packaging process by automating steps like flattening node_modules and using Windows SDK tools. ```sh npm install -g electron-windows-store ``` -------------------------------- ### Run IPC Unit Tests Example (npm) Source: https://github.com/discord/electron/blob/main/docs/development/testing.md An example demonstrating how to run only the unit tests specifically related to Inter-Process Communication (IPC) by using `-g ipc` as the pattern. ```shell npm run test -- -g ipc ``` -------------------------------- ### Installing Electron as Development Dependency - npm Source: https://github.com/discord/electron/blob/main/docs/tutorial/installation.md This command installs Electron as a development dependency in your current project. This is the preferred method for most applications, ensuring the Electron version is tracked with the project. ```sh npm install electron --save-dev ``` -------------------------------- ### Requiring Installed Node.js Module - JavaScript Source: https://github.com/discord/electron/blob/main/docs/tutorial/quick-start.md Imports a specific module or client ('aws-sdk/clients/s3') from a Node.js package that has been installed as a project dependency. This makes the module's functionality available for use within the Electron application. ```javascript const S3 = require('aws-sdk/clients/s3') ``` -------------------------------- ### Creating BrowserWindow - JavaScript Source: https://github.com/discord/electron/blob/main/docs/tutorial/quick-start.md Creates a new Electron browser window using the `BrowserWindow` class. This class is only accessible and intended for use within the Electron Main process. It instantiates a window where web content can be loaded. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() ``` -------------------------------- ### Start Electron REPL (Local Install) - sh Source: https://github.com/discord/electron/blob/main/docs/tutorial/repl.md This command starts Electron in interactive (REPL) mode for the main process when Electron is installed locally as a project dependency. It executes the Electron binary located in the `node_modules/.bin` directory. ```sh ./node_modules/.bin/electron --interactive ``` -------------------------------- ### Setting up Desktop App Converter - PowerShell Source: https://github.com/discord/electron/blob/main/docs/tutorial/windows-store-guide.md Runs the setup script for the Windows Desktop App Converter tool, which is an alternative method for packaging desktop applications including Electron apps into .appx format. It requires specifying the path to a Windows base image file (`BaseImage-14316.wim`) used for the container environment. This must be run from an elevated PowerShell after downloading the necessary files. ```powershell .\DesktopAppConverter.ps1 -Setup -BaseImage .\BaseImage-14316.wim ``` -------------------------------- ### Start Electron REPL (Global Install) - sh Source: https://github.com/discord/electron/blob/main/docs/tutorial/repl.md This command starts Electron in interactive (REPL) mode for the main process when Electron is installed globally. It assumes the `electron` executable is available in the system's PATH. ```sh electron --interactive ``` -------------------------------- ### Requiring Electron Module - JavaScript Source: https://github.com/discord/electron/blob/main/docs/tutorial/quick-start.md Imports the core 'electron' module, providing access to various Electron APIs. This is a fundamental step for utilizing Electron's features and can be done in both the Main and Renderer processes. ```javascript const electron = require('electron') ``` -------------------------------- ### Create Renderer Process HTML Page Source: https://github.com/discord/electron/blob/main/docs/tutorial/quick-start.md This HTML code defines the web page that will be displayed in the Electron application's browser window. It includes basic HTML structure, sets a title, configures a Content Security Policy, and displays version information for Node.js, Chrome, and Electron by executing small JavaScript snippets within the page. ```html Hello World!

Hello World!

We are using node , Chrome , and Electron . ``` -------------------------------- ### Make Distributable Package with Electron Forge in Shell Source: https://github.com/discord/electron/blob/main/docs/tutorial/quick-start.md This shell command runs the 'make' script, which is typically added to package.json by Electron Forge's import command. It instructs Electron Forge to package and create a distributable version of the application, outputting the result in the 'out' folder. ```sh npm run make ``` -------------------------------- ### Starting Electron ChromeDriver server for WebdriverIO (sh) Source: https://github.com/discord/electron/blob/main/docs/tutorial/using-selenium-and-webdriver.md Command to execute the `chromedriver` binary for WebdriverIO, specifying the `--url-base` and `--port` arguments. This starts the server configured for WebdriverIO clients. Requires `electron-chromedriver` to be installed. ```sh ./node_modules/.bin/chromedriver --url-base=wd/hub --port=9515 Starting ChromeDriver (v2.10.291558) on port 9515 Only local connections are allowed. ``` -------------------------------- ### Starting Electron ChromeDriver server for WebDriverJs (sh) Source: https://github.com/discord/electron/blob/main/docs/tutorial/using-selenium-and-webdriver.md Command to execute the installed `chromedriver` binary from the `node_modules/.bin` directory. This starts the ChromeDriver server on a default port (usually 9515), allowing WebDriver clients to connect. Requires `electron-chromedriver` to be installed. ```sh ./node_modules/.bin/chromedriver Starting ChromeDriver (v2.10.291558) on port 9515 Only local connections are allowed. ``` -------------------------------- ### Installing Electron with Specific Architecture - npm Source: https://github.com/discord/electron/blob/main/docs/tutorial/installation.md This command installs Electron specifically for the 'ia32' architecture, overriding the default architecture detected by npm. Useful when developing for a different architecture than your build machine. ```shell npm install --arch=ia32 electron ``` -------------------------------- ### Installing Electron with Specific Platform - npm Source: https://github.com/discord/electron/blob/main/docs/tutorial/installation.md This command installs Electron specifically for the 'win32' platform, overriding the default platform detected by npm. Useful for cross-platform development or building on a different OS. ```shell npm install --platform=win32 electron ``` -------------------------------- ### Configuring Custom Electron Mirror (China CDN) - shell Source: https://github.com/discord/electron/blob/main/docs/tutorial/installation.md Sets the ELECTRON_MIRROR environment variable to use the China CDN mirror for downloading Electron binaries during installation. This is useful in regions where the default GitHub releases download is slow or inaccessible. ```shell ELECTRON_MIRROR="https://cdn.npm.taobao.org/dist/electron/" ``` -------------------------------- ### Define Main Electron Script in JavaScript Source: https://github.com/discord/electron/blob/main/docs/tutorial/quick-start.md This JavaScript code defines the main process script for an Electron application. It imports necessary modules, creates a browser window to load an HTML file, manages the application's lifecycle events (ready, window-all-closed, activate), and includes dev tools for debugging. Node.js integration is enabled in the window's web preferences. ```js const { app, BrowserWindow } = require('electron') function createWindow () { const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) win.loadFile('index.html') win.webContents.openDevTools() } app.whenReady().then(createWindow) app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit() } }) app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) { createWindow() } }) ``` -------------------------------- ### Reading Directory with Node.js fs - JavaScript Source: https://github.com/discord/electron/blob/main/docs/tutorial/quick-start.md Demonstrates accessing the Node.js file system ('fs') module within an Electron application. It reads the synchronous contents of the root directory ('/') and prints them to the console. Requires Node.js integration to be enabled if run in the Renderer process. ```javascript const fs = require('fs') const root = fs.readdirSync('/') console.log(root) ``` -------------------------------- ### Installing Electron with Unsafe Permissions - sh Source: https://github.com/discord/electron/blob/main/docs/tutorial/installation.md Installs Electron using 'sudo' and the '--unsafe-perm=true' flag. This can resolve installation errors related to permissions (EACCESS) but should be used with caution as it disables npm's safety checks regarding running scripts as root. ```sh sudo npm install electron --unsafe-perm=true ``` -------------------------------- ### Verify Node.js and npm Versions (PowerShell) Source: https://github.com/discord/electron/blob/main/docs/tutorial/development-environment.md This snippet provides PowerShell commands to verify the successful installation of Node.js and npm on Windows. It executes `node -v` to print the installed Node.js version and `npm -v` to print the installed npm version, confirming that the executables are available and functioning correctly in the PowerShell environment. ```powershell node -v npm -v ``` -------------------------------- ### Handling IPC Invoke in Main Process - JavaScript Source: https://github.com/discord/electron/blob/main/docs/tutorial/quick-start.md Sets up a handler in the Electron Main process to respond to an `ipcRenderer.invoke` call from a Renderer process. It listens on the 'perform-action' channel and executes code on behalf of the renderer, providing a mechanism for safe bidirectional communication. ```javascript // In the Main process const { ipcMain } = require('electron') ipcMain.handle('perform-action', (event, ...args) => { // ... do actions on behalf of the Renderer }) ``` -------------------------------- ### Configuring Custom Electron Mirror (China Non-CDN) - shell Source: https://github.com/discord/electron/blob/main/docs/tutorial/installation.md Sets both ELECTRON_MIRROR and ELECTRON_CUSTOM_DIR environment variables to use the China non-CDN mirror and customize the directory format for downloading Electron binaries. This provides an alternative download source and path structure. ```shell ELECTRON_MIRROR="https://npm.taobao.org/mirrors/electron/" ELECTRON_CUSTOM_DIR="{{ version }}" ``` -------------------------------- ### Getting Electron Source Code Source: https://github.com/discord/electron/blob/main/docs/development/build-instructions-gn.md Creates a directory for the Electron source code, navigates into it, configures gclient to manage the repository and its dependencies, and then syncs the code, including branch heads and tags. ```sh mkdir electron && cd electron gclient config --name "src/electron" --unmanaged https://github.com/electron/electron gclient sync --with_branch_heads --with_tags ``` -------------------------------- ### Installing electron-installer-snap; Shell Source: https://github.com/discord/electron/blob/main/docs/tutorial/snapcraft.md Installs the `electron-installer-snap` tool as a development dependency using npm. This package simplifies the creation of Snap packages for Electron applications. ```sh npm install --save-dev electron-installer-snap ``` -------------------------------- ### Skipping Electron Binary Download - sh Source: https://github.com/discord/electron/blob/main/docs/tutorial/installation.md Sets the ELECTRON_SKIP_BINARY_DOWNLOAD environment variable to 1 before running 'npm install'. This prevents the Electron binary from being downloaded during the npm installation process, useful in CI environments or when only package metadata is needed. ```sh ELECTRON_SKIP_BINARY_DOWNLOAD=1 npm install ``` -------------------------------- ### Installing Snap package locally; Shell Source: https://github.com/discord/electron/blob/main/docs/tutorial/snapcraft.md Installs the locally built `.snap` package using the `snap install` command with the `--dangerous` flag. This flag is necessary for installing snaps that are not signed and published in the Snap Store. ```sh sudo snap install electron-packager-hello-world_0.1_amd64.snap --dangerous ``` -------------------------------- ### Configuring Xvfb on Travis CI (yml) Source: https://github.com/discord/electron/blob/main/docs/tutorial/testing-on-headless-ci.md This YAML snippet shows the necessary configuration for a `.travis.yml` file to enable testing Electron applications on Travis CI. It installs the `xvfb` package using `apt`, sets the required `DISPLAY` environment variable to `:99.0`, and starts the Xvfb server on display 99 with a screen resolution of 1024x768 and 24-bit color depth, redirecting output to `/dev/null` and running it in the background. ```yaml addons: apt: packages: - xvfb install: - export DISPLAY=':99.0' - Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 & ``` -------------------------------- ### Initializing Electron Crash Reporter (JavaScript) Source: https://github.com/discord/electron/blob/main/docs/api/crash-reporter.md This snippet demonstrates the basic setup to start the Electron crash reporter. It requires the `crashReporter` module and calls the `start` method, providing the `submitURL` where crash reports should be sent. This should be called as early as possible in the application's main process. ```JavaScript const { crashReporter } = require('electron') crashReporter.start({ submitURL: 'https://your-domain.com/url-to-submit' }) ``` -------------------------------- ### Installing Build Dependencies on Ubuntu (Shell) Source: https://github.com/discord/electron/blob/main/docs/development/build-instructions-linux.md This `apt-get` command installs the essential development libraries and tools required to build Electron on Ubuntu distributions. It includes build tools, specific library headers (GTK 3, libnotify, etc.), and other necessary packages like `python-dbusmock` and `openjdk-8-jre`. ```sh $ sudo apt-get install build-essential clang libdbus-1-dev libgtk-3-dev \ libnotify-dev libgnome-keyring-dev \ libasound2-dev libcap-dev libcups2-dev libxtst-dev \ libxss1 libnss3-dev gcc-multilib g++-multilib curl \ gperf bison python-dbusmock openjdk-8-jre ``` -------------------------------- ### Invoking IPC in Renderer Process - JavaScript Source: https://github.com/discord/electron/blob/main/docs/tutorial/quick-start.md Initiates an asynchronous request from the Electron Renderer process to the Main process using `ipcRenderer.invoke`. It sends arguments via the 'perform-action' channel and expects a response from the corresponding `ipcMain.handle` listener in the Main process. ```javascript // In the Renderer process const { ipcRenderer } = require('electron') ipcRenderer.invoke('perform-action', ...args) ``` -------------------------------- ### Structuring Class API References Source: https://github.com/discord/electron/blob/main/docs/styleguide.md This extensive snippet provides an example of documenting a class within an API reference, showing how to define the class chapter, instance events, methods, and properties, including how related classes (like 'Cookies' within 'session') should be structured. ```markdown # session ## Methods ### session.fromPartition(partition) ## Static Properties ### session.defaultSession ## Class: Session ### Instance Events #### Event: 'will-download' ### Instance Methods #### `ses.getCacheSize()` ### Instance Properties #### `ses.cookies` ## Class: Cookies ### Instance Methods #### `cookies.get(filter, callback)` ``` -------------------------------- ### Installing clang-format and git-clang-format (Shell) Source: https://github.com/discord/electron/blob/main/docs/development/clang-format.md This command installs the clang-format and git-clang-format tools globally using npm. These tools are required for automatic C++ code formatting according to Electron's style guide. ```Shell npm install -g clang-format ``` -------------------------------- ### VS 2017 x64_arm64 Cross-Compile Command Prompt Output Source: https://github.com/discord/electron/blob/main/docs/tutorial/windows-arm.md Example output displayed when successfully initializing a Visual Studio 2017 Developer Command Prompt for cross-compilation from x64 to arm64, confirming the environment setup. ```Batch ********************************************************************** ** Visual Studio 2017 Developer Command Prompt v15.9.15 ** Copyright (c) 2017 Microsoft Corporation ********************************************************************** [vcvarsall.bat] Environment initialized for: 'x64_arm64' ``` -------------------------------- ### Verify Node.js and npm Versions (sh) Source: https://github.com/discord/electron/blob/main/docs/tutorial/development-environment.md This snippet provides standard shell commands (`sh`) to verify the successful installation of Node.js and npm on Unix-like systems (macOS, Linux). It runs `node -v` to display the Node.js version and `npm -v` to display the npm version, confirming they are installed and accessible in the system's PATH. ```sh node -v npm -v ``` -------------------------------- ### Running installed Snap application; Shell Source: https://github.com/discord/electron/blob/main/docs/tutorial/snapcraft.md Launches the Electron application that has been installed as a Snap package. The command is the name specified in the `snapcraft.yaml` file's `apps` section. ```sh electron-packager-hello-world ``` -------------------------------- ### Main Process Entry Point Example for remote.require (Javascript) Source: https://github.com/discord/electron/blob/main/docs/api/remote.md Provides a basic example of an Electron main process entry point file (`main/index.js`) that requires the `app` module and waits for the `ready` event. This snippet is part of the context for demonstrating how `remote.require` resolves paths relative to this main entry point. ```Javascript // main process: main/index.js const { app } = require('electron') app.whenReady().then(() => { /* ... */ }) ``` -------------------------------- ### Setting PowerShell Execution Policy - PowerShell Source: https://github.com/discord/electron/blob/main/docs/tutorial/windows-store-guide.md Modifies the PowerShell execution policy to allow running local scripts without restrictions, which is necessary for executing the `DesktopAppConverter.ps1` setup script. This command should be run from an elevated PowerShell prompt before attempting to set up the Desktop App Converter. ```powershell Set-ExecutionPolicy bypass ``` -------------------------------- ### Installing Spectron npm package (sh) Source: https://github.com/discord/electron/blob/main/docs/tutorial/using-selenium-and-webdriver.md Command to install Spectron as a development dependency using npm. Spectron is the official testing framework for Electron based on WebdriverIO. ```sh npm install --save-dev spectron ``` -------------------------------- ### Check Electron Python TLS Support (sh) Source: https://github.com/discord/electron/blob/main/docs/development/build-instructions-macos.md Runs a script provided by Electron to verify that your Python 2.7 setup supports TLS 1.2, which is required for building Electron. This command uses npx to execute the script without needing it installed globally. ```sh npx @electron/check-python-tls ``` -------------------------------- ### Installing Selenium WebDriverJs npm package (sh) Source: https://github.com/discord/electron/blob/main/docs/tutorial/using-selenium-and-webdriver.md Command to install the `selenium-webdriver` package using npm. This package provides the JavaScript bindings for the Selenium WebDriver API. ```sh npm install selenium-webdriver ``` -------------------------------- ### Installing WebdriverIO npm package (sh) Source: https://github.com/discord/electron/blob/main/docs/tutorial/using-selenium-and-webdriver.md Command to install the core `webdriverio` package using npm. This package provides the WebdriverIO framework for automated testing. ```sh npm install webdriverio ``` -------------------------------- ### Run All Unit Tests (npm) Source: https://github.com/discord/electron/blob/main/docs/development/testing.md Executes all unit tests for Electron using an npm script. The tests are structured as an Electron application located in the `spec` folder. ```shell npm run test ``` -------------------------------- ### Example Electron App Directory Structure Shell Source: https://github.com/discord/electron/blob/main/docs/api/web-contents.md Illustrates a typical directory structure for a basic Electron application, showing the placement of the `package.json`, main process file (`main.js`), and the main HTML file (`index.html`) within the project root. ```sh | root | - package.json | - src | - main.js | - index.html ``` -------------------------------- ### Installing ARM Cross-Compilation Deps on Ubuntu (Shell) Source: https://github.com/discord/electron/blob/main/docs/development/build-instructions-linux.md This `apt-get` command installs the specific packages needed on Ubuntu for cross-compiling Electron to the `arm` architecture. It includes the necessary cross-development libraries and the appropriate cross-compiler. ```sh $ sudo apt-get install libc6-dev-armhf-cross linux-libc-dev-armhf-cross \ g++-arm-linux-gnueabihf ``` -------------------------------- ### Installing ARM64 Cross-Compilation Deps on Ubuntu (Shell) Source: https://github.com/discord/electron/blob/main/docs/development/build-instructions-linux.md This `apt-get` command installs the necessary packages on Ubuntu for cross-compiling Electron to the `arm64` architecture. It provides the required cross-development libraries and the `aarch64` cross-compiler. ```sh $ sudo apt-get install libc6-dev-arm64-cross linux-libc-dev-arm64-cross \ g++-aarch64-linux-gnu ``` -------------------------------- ### Initializing Electron Main Process JavaScript Source: https://github.com/discord/electron/blob/main/docs/api/synopsis.md Demonstrates a basic Electron main process script. It requires `app` and `BrowserWindow` from the `electron` module, waits for the app to be ready, creates a `BrowserWindow` instance with specified dimensions, and loads a URL into the window. ```javascript const { app, BrowserWindow } = require('electron') let win = null app.whenReady().then(() => { win = new BrowserWindow({ width: 800, height: 600 }) win.loadURL('https://github.com') }) ``` -------------------------------- ### Installing asar CLI Utility - Shell Source: https://github.com/discord/electron/blob/main/docs/tutorial/application-packaging.md This command installs the asar command-line interface globally using npm, which is required to create and manage asar archives manually. ```shell npm install -g asar ``` -------------------------------- ### Install surf-build Tool Shell Source: https://github.com/discord/electron/blob/main/docs/tutorial/application-distribution.md This command installs the `surf-build` tool globally using npm. `surf-build` is a utility used for creating custom Electron releases, typically from a fork. ```shell npm install -g surf-build@latest ``` -------------------------------- ### Running Tests with Extra Flags Source: https://github.com/discord/electron/blob/main/docs/development/build-instructions-gn.md Executes the test suite using the 'npm run test' script and passes additional flags to the Electron binary. This example enables logging and filters tests to run only those matching 'BrowserWindow module'. ```sh npm run test -- \ --enable-logging -g 'BrowserWindow module' ``` -------------------------------- ### Running electron-installer-snap; Shell Source: https://github.com/discord/electron/blob/main/docs/tutorial/snapcraft.md Executes the `electron-installer-snap` command via npx, specifying the path to the packaged Electron application output. This command builds the `.snap` file from the packaged source. ```sh npx electron-installer-snap --src=out/myappname-linux-x64 ``` -------------------------------- ### Start and Stop Electron contentTracing in JavaScript Source: https://github.com/discord/electron/blob/main/docs/api/content-tracing.md This snippet demonstrates how to start content tracing with all categories included (`*`), wait for a fixed duration, and then stop tracing, logging the path to the resulting trace file. It requires waiting for the Electron application's `ready` event. ```javascript const { app, contentTracing } = require('electron') app.whenReady().then(() => { (async () => { await contentTracing.startRecording({ include_categories: ['*'] }) console.log('Tracing started') await new Promise(resolve => setTimeout(resolve, 5000)) const path = await contentTracing.stopRecording() console.log('Tracing data recorded to ' + path) })() }) ``` -------------------------------- ### Example Preload Script for Sandboxed Renderer in Electron Source: https://github.com/discord/electron/blob/main/docs/api/sandbox-option.md This is an example of a `preload.js` script intended for use with a sandboxed renderer. It demonstrates how to access a limited set of Node.js/Electron APIs (like `ipcRenderer`) available in the preload scope, despite the main renderer having Node.js disabled. The script intercepts `window.open` to send IPC messages. ```JavaScript // This file is loaded whenever a javascript context is created. It runs in a // private scope that can access a subset of Electron renderer APIs. Without // contextIsolation enabled, it's possible to accidentally leak privileged // globals like ipcRenderer to web content. const { ipcRenderer } = require('electron') const defaultWindowOpen = window.open window.open = function customWindowOpen (url, ...args) { ipcRenderer.send('report-window-open', location.origin, url, args) return defaultWindowOpen(url + '?from_electron=1', ...args) } ``` -------------------------------- ### Run JavaScript Linting (npm) Source: https://github.com/discord/electron/blob/main/docs/development/testing.md Executes the JavaScript linter (`standard`) on the Electron codebase and unit tests using an npm script to ensure compliance with the project's coding style. ```shell npm run lint-js ``` -------------------------------- ### Run Python Linting (npm) Source: https://github.com/discord/electron/blob/main/docs/development/testing.md Executes the Python linter (`pylint`) using an npm script to check compliance with the Electron project's Python coding style. ```shell npm run lint-py ``` -------------------------------- ### Child Process App Sandbox Entitlements (XML) Source: https://github.com/discord/electron/blob/main/docs/tutorial/mac-app-store-submission-guide.md Defines the entitlements required for child processes within the sandboxed Electron application, such as framework helpers. It enables the app sandbox and allows inheritance of entitlements. ```XML com.apple.security.app-sandbox com.apple.security.inherit ``` -------------------------------- ### Run JavaScript Linting with Args (npm) Source: https://github.com/discord/electron/blob/main/docs/development/testing.md Runs the JavaScript linter (`standard`) using npm, allowing additional arguments to be passed directly to the `standard` command by including them after the double dash (`--`). ```shell npm run lint-js -- ``` -------------------------------- ### Create Node Headers Directory (Windows) Source: https://github.com/discord/electron/blob/main/docs/development/testing.md Creates the required directory structure (`gen\node_headers\Release`) within the build output folder. This is where the copied `node.lib` file will be placed. ```powershell mkdir gen\node_headers\Release ``` -------------------------------- ### Run C++ Linting (npm) Source: https://github.com/discord/electron/blob/main/docs/development/testing.md Executes the C++ linter (`cpplint` script) using an npm script to check compliance with the Electron project's C++ coding style. ```shell npm run lint-cpp ``` -------------------------------- ### Running electron-windows-store Conversion - PowerShell Source: https://github.com/discord/electron/blob/main/docs/tutorial/windows-store-guide.md Executes the `electron-windows-store` command from an elevated PowerShell prompt to convert a packaged Electron application into a Windows Store .appx package. It requires specifying the input directory of the packaged app, the desired output directory for the .appx, the package version, and the package name. ```powershell electron-windows-store ` --input-directory C:\myelectronapp ` --output-directory C:\output\myelectronapp ` --package-version 1.0.0.0 ` --package-name myelectronapp ``` -------------------------------- ### Syncing gclient for Windows on Arm (CMD) Source: https://github.com/discord/electron/blob/main/docs/development/build-instructions-gn.md Sets the ELECTRON_BUILDING_WOA environment variable to 1 and then runs 'gclient sync -f' with branch heads and tags. This prepares the environment and synchronizes dependencies specifically for building Electron for Windows on Arm (WoA) using the Command Prompt. ```bat set ELECTRON_BUILDING_WOA=1 gclient sync -f --with_branch_heads --with_tags ``` -------------------------------- ### Structuring Module Methods and Events in API References Source: https://github.com/discord/electron/blob/main/docs/styleguide.md This snippet illustrates how to structure the documentation for a module that is not a class, listing its methods and events under dedicated 'Methods' and 'Events' chapters with appropriate heading levels. ```markdown # autoUpdater ## Events ### Event: 'error' ## Methods ### `autoUpdater.setFeedURL(url[, requestHeaders])` ``` -------------------------------- ### Spawning Electron Programmatically Javascript Source: https://github.com/discord/electron/blob/main/README.md Demonstrates how to require the `electron` package within a Node.js script to get the path to the Electron binary and then use Node's `child_process` module to spawn an Electron instance. ```javascript const electron = require('electron') const proc = require('child_process') // will print something similar to /Users/maf/.../Electron console.log(electron) // spawn Electron const child = proc.spawn(electron) ``` -------------------------------- ### Snapcraft app command with desktop-launch; YAML Source: https://github.com/discord/electron/blob/main/docs/tutorial/snapcraft.md Defines the `command` for the application within a `snapcraft.yaml` using the `desktop-launch` helper, typically for `strict` confinement. It sets environment variables and points to the application's entry point. ```yaml apps: myApp: # Correct the TMPDIR path for Chromium Framework/Electron to ensure # libappindicator has readable resources. command: env TMPDIR=$XDG_RUNTIME_DIR PATH=/usr/local/bin:${PATH} ${SNAP}/bin/desktop-launch $SNAP/myApp/desktop desktop: usr/share/applications/desktop.desktop ``` -------------------------------- ### Documenting Platform-Specific Parameters Source: https://github.com/discord/electron/blob/main/docs/styleguide.md This snippet illustrates how to denote parameters that are specific to certain platforms (macOS, Windows, or Linux) by listing the applicable platforms in italics after the parameter's type. ```markdown * `animate` Boolean (optional) _macOS_ _Windows_ - Animate the thing. ``` -------------------------------- ### Initializing Electron BrowserWindow and Loading Content (Javascript) Source: https://github.com/discord/electron/blob/main/docs/api/browser-window.md Demonstrates creating a new Electron BrowserWindow instance with specified dimensions. It shows how to load content either from a remote URL using `loadURL('https://...')` or from a local HTML file using `loadURL('file://...')`. Requires the `electron` module. ```javascript // In the main process. const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 600 }) // Load a remote URL win.loadURL('https://github.com') // Or load a local HTML file win.loadURL(`file://${__dirname}/app/index.html`) ``` -------------------------------- ### Example HTML Form for POST Data Limitation Source: https://github.com/discord/electron/blob/main/docs/api/structures/post-body.md Provides an example of an HTML form using method="POST" and enctype="application/x-www-form-urlencoded". This snippet illustrates a limitation where keys starting with '--' are not correctly handled, potentially causing it to be submitted as multipart/form-data unexpectedly when nativeWindowOpen is disabled. ```html
``` -------------------------------- ### Programmatic electron-installer-snap usage; JavaScript Source: https://github.com/discord/electron/blob/main/docs/tutorial/snapcraft.md Demonstrates how to use the `electron-installer-snap` module programmatically within a Node.js script. It takes an options object and returns a promise that resolves with the path to the created snap file. ```js const snap = require('electron-installer-snap') snap(options) .then(snapPath => console.log(`Created snap at ${snapPath}!`)) ``` -------------------------------- ### Copy electron.lib to node.lib (Windows) Source: https://github.com/discord/electron/blob/main/docs/development/testing.md Copies the generated `electron.lib` file from the build output directory to the newly created `gen\node_headers\Release` folder, renaming it to `node.lib`. This step is crucial for the Windows testing setup. ```powershell copy electron.lib gen\node_headers\Release\node.lib ``` -------------------------------- ### Syncing gclient for Windows on Arm (PowerShell) Source: https://github.com/discord/electron/blob/main/docs/development/build-instructions-gn.md Sets the ELECTRON_BUILDING_WOA environment variable to 1 using PowerShell syntax and then runs 'gclient sync -f' with branch heads and tags. This prepares the environment and synchronizes dependencies specifically for building Electron for Windows on Arm (WoA) using PowerShell. ```powershell $env:ELECTRON_BUILDING_WOA=1 gclient sync -f --with_branch_heads --with_tags ``` -------------------------------- ### Building Release Configuration with Ninja Source: https://github.com/discord/electron/blob/main/docs/development/build-instructions-gn.md Compiles the Electron project using the Ninja build system, targeting the 'electron' target within the 'out/Release' build directory. ```sh ninja -C out/Release electron ``` -------------------------------- ### Building Testing Configuration with Ninja Source: https://github.com/discord/electron/blob/main/docs/development/build-instructions-gn.md Compiles the Electron project using the Ninja build system, targeting the 'electron' target within the 'out/Testing' build directory. ```sh ninja -C out/Testing electron ``` -------------------------------- ### Handling found-in-page event and starting search in Electron webview (JavaScript) Source: https://github.com/discord/electron/blob/main/docs/api/webview-tag.md This example shows how to listen for the `found-in-page` event to potentially stop a find operation (`webview.stopFindInPage`) and how to initiate a new search for text within the webview's guest page using `webview.findInPage`. ```javascript const webview = document.querySelector('webview') webview.addEventListener('found-in-page', (e) => { webview.stopFindInPage('keepSelection') }) const requestId = webview.findInPage('test') console.log(requestId) ``` -------------------------------- ### Showing Packaged Electron App Structure - plaintext Source: https://github.com/discord/electron/blob/main/docs/tutorial/windows-store-guide.md Illustrates the typical directory and file structure of an Electron application after being packaged by a tool like `electron-packager`. This structure represents the input expected by the `electron-windows-store` conversion tool, showing the executable, resources, and dependencies. ```plaintext ├── Ghost.exe ├── LICENSE ├── content_resources_200_percent.pak ├── content_shell.pak ├── d3dcompiler_47.dll ├── ffmpeg.dll ├── icudtl.dat ├── libEGL.dll ├── libGLESv2.dll ├── locales │   ├── am.pak │   ├── ar.pak │   ├── [...] ├── node.dll ├── resources │   └── app.asar ├── v8_context_snapshot.bin ├── squirrel.exe └── ui_resources_200_percent.pak ``` -------------------------------- ### Setting up Git Cache Source: https://github.com/discord/electron/blob/main/docs/development/build-instructions-gn.md Configures a shared git cache directory to speed up subsequent checkouts of the Electron repository and its dependencies using `gclient`. This is beneficial when working with multiple local copies of the Electron source code. ```sh export GIT_CACHE_PATH="${HOME}/.git_cache" mkdir -p "${GIT_CACHE_PATH}" ``` -------------------------------- ### Setting and Getting BrowserWindow Bounds in Electron (JavaScript) Source: https://github.com/discord/electron/blob/main/docs/api/browser-window.md This snippet demonstrates how to use the `win.setBounds()` method to set the position and size of an Electron BrowserWindow. It shows examples of setting all bounds properties and partially updating them. It also includes a call to `win.getBounds()` to retrieve and log the current window bounds. ```JavaScript const { BrowserWindow } = require('electron') const win = new BrowserWindow() // set all bounds properties win.setBounds({ x: 440, y: 225, width: 800, height: 600 }) // set a single bounds property win.setBounds({ width: 100 }) // { x: 440, y: 225, width: 100, height: 600 } console.log(win.getBounds()) ``` -------------------------------- ### Initializing Electron Tray with Context Menu JavaScript Source: https://github.com/discord/electron/blob/main/docs/api/tray.md This snippet demonstrates how to create a new `Tray` icon, build a context menu using `Menu.buildFromTemplate`, set a tooltip, and assign the context menu to the tray icon. It requires the Electron `app`, `Menu`, and `Tray` modules. ```javascript const { app, Menu, Tray } = require('electron') let tray = null app.whenReady().then(() => { tray = new Tray('/path/to/my/icon') const contextMenu = Menu.buildFromTemplate([ { label: 'Item1', type: 'radio' }, { label: 'Item2', type: 'radio' }, { label: 'Item3', type: 'radio', checked: true }, { label: 'Item4', type: 'radio' } ]) tray.setToolTip('This is my application.') tray.setContextMenu(contextMenu) }) ``` -------------------------------- ### Creating a Basic Electron BrowserWindow Instance JS Source: https://github.com/discord/electron/blob/main/docs/api/browser-window.md This snippet shows the basic steps to create a new `BrowserWindow` instance with specified dimensions and load a URL into it. It demonstrates requiring the `BrowserWindow` class from the `electron` module and using the `new` keyword to create an instance, followed by loading content using `win.loadURL()`. ```javascript const { BrowserWindow } = require('electron') // In this example `win` is our instance const win = new BrowserWindow({ width: 800, height: 600 }) win.loadURL('https://github.com') ``` -------------------------------- ### Running Full Electron Test Suite | Shell Source: https://github.com/discord/electron/blob/main/docs/development/pull-requests.md Executes the npm script named 'test' defined in the project's 'package.json'. This typically runs the entire test suite for the Electron project to verify code correctness and prevent regressions. Requires Node.js and npm installed. ```Shell $ npm run test ``` -------------------------------- ### Running Specific Electron Tests by Pattern | Shell Source: https://github.com/discord/electron/blob/main/docs/development/pull-requests.md Executes the npm script named 'test', passing the '-match=menu' argument. This runs only the test specification files whose paths or names match the pattern 'menu', useful for focusing on specific areas during development. Requires Node.js and npm installed. ```Shell $ npm run test -match=menu ``` -------------------------------- ### Handling Drag Start in Electron Renderer Source: https://github.com/discord/electron/blob/main/docs/tutorial/native-file-drag-drop.md This JavaScript snippet, intended for the renderer process (`renderer.js`), demonstrates how to capture the `ondragstart` event on the designated HTML element. It prevents the default browser drag behavior and sends an IPC message ('ondragstart') to the main process, including the absolute path of the item to be dragged using `ipcRenderer`. ```javascript const { ipcRenderer } = require('electron') document.getElementById('drag').ondragstart = (event) => { event.preventDefault() ipcRenderer.send('ondragstart', '/absolute/path/to/the/item') } ``` -------------------------------- ### Initializing Electron Main Process with Destructuring from Module JavaScript Source: https://github.com/discord/electron/blob/main/docs/api/synopsis.md Demonstrates an alternative method for using destructuring assignment with the `electron` module. It first requires the entire `electron` module and then extracts the `app` and `BrowserWindow` properties using destructuring. Initializes an app, creates a window, and loads a URL. ```javascript const electron = require('electron') const { app, BrowserWindow } = electron let win app.whenReady().then(() => { win = new BrowserWindow() win.loadURL('https://github.com') }) ``` -------------------------------- ### Pulling Latest Code and Syncing Dependencies Source: https://github.com/discord/electron/blob/main/docs/development/build-instructions-gn.md Navigates into the 'src/electron' directory, pulls the latest changes from the remote repository, and then runs 'gclient sync -f' to ensure all dependencies match the updated DEPS file. ```sh cd src/electron git pull gclient sync -f ``` -------------------------------- ### Defining UI for Dark Mode Toggling in Electron HTML Source: https://github.com/discord/electron/blob/main/docs/tutorial/dark-mode.md This HTML snippet defines the user interface for the example application. It includes a title, a paragraph displaying the current theme source, and two buttons to toggle dark mode and reset the theme to the system default. It links to external CSS for styling and a renderer process script for interactivity. ```html Hello World!

Hello World!

Current theme source: System

``` -------------------------------- ### Install Python pyobjc module with pip (sh) Source: https://github.com/discord/electron/blob/main/docs/development/build-instructions-macos.md Installs the pyobjc module for Python using pip. This module is required if you are using a Homebrew-provided Python installation for building Electron. ```sh pip install pyobjc ``` -------------------------------- ### Installing Latest Stable Electron via npm (sh) Source: https://github.com/discord/electron/blob/main/docs/tutorial/electron-versioning.md This command installs the most recent stable release of Electron into the current project. It saves the dependency to the `devDependencies` section of the `package.json` file. Requires Node.js and npm installed. ```sh npm install --save-dev electron ``` -------------------------------- ### Relaunching Electron app with Arguments (JavaScript) Source: https://github.com/discord/electron/blob/main/docs/api/app.md Provides an example of how to relaunch the Electron application using `app.relaunch()`. It configures the relaunch to pass the current command-line arguments (excluding the first, which is the executable path) plus an additional `--relaunch` argument to the new instance. It then immediately exits the current instance with code 0. ```javascript const { app } = require('electron') app.relaunch({ args: process.argv.slice(1).concat(['--relaunch']) }) app.exit(0) ``` -------------------------------- ### Initializing Tray and Window with File Paths in Electron JavaScript Source: https://github.com/discord/electron/blob/main/docs/api/native-image.md This snippet demonstrates how to initialize Electron's `Tray` and `BrowserWindow` elements by providing direct file paths to image assets for their icons. It requires the `electron` module and uses example file paths. The created instances and the paths are then logged to the console, showing a common way to use images without explicitly creating `NativeImage` instances first. ```javascript const { BrowserWindow, Tray } = require('electron') const appIcon = new Tray('/Users/somebody/images/icon.png') const win = new BrowserWindow({ icon: '/Users/somebody/images/window.png' }) console.log(appIcon, win) ``` -------------------------------- ### Defining Snapcraft config from source; YAML Source: https://github.com/discord/electron/blob/main/docs/tutorial/snapcraft.md Configures a `snapcraft.yaml` file to build a Snap package directly from Electron application source code. It specifies metadata, base, confinement, application command, required plugs, and uses `electron-packager` within the build process. ```yaml name: electron-packager-hello-world version: '0.1' summary: Hello World Electron app description: | Simple Hello World Electron app as an example base: core18 confinement: strict grade: stable apps: electron-packager-hello-world: command: electron-quick-start/electron-quick-start --no-sandbox extensions: [gnome-3-34] plugs: - browser-support - network - network-bind environment: # Correct the TMPDIR path for Chromium Framework/Electron to ensure # libappindicator has readable resources. TMPDIR: $XDG_RUNTIME_DIR parts: electron-quick-start: plugin: nil source: https://github.com/electron/electron-quick-start.git override-build: | npm install electron electron-packager npx electron-packager . --overwrite --platform=linux --output=release-build --prune=true cp -rv ./electron-quick-start-linux-* $SNAPCRAFT_PART_INSTALL/electron-quick-start build-snaps: - node/14/stable build-packages: - unzip stage-packages: - libnss3 - libnspr4 ``` -------------------------------- ### Defining Snapcraft config from .deb; YAML Source: https://github.com/discord/electron/blob/main/docs/tutorial/snapcraft.md Configures a `snapcraft.yaml` file to build a Snap package using an existing `.deb` package as the primary source. It defines metadata, confinement, and parts that stage the `.deb` contents and necessary libraries. ```yaml name: myApp version: '2.0.0' summary: A little description for the app. description: | You know what? This app is amazing! It does all the things for you. Some say it keeps you young, maybe even happy. grade: stable confinement: classic parts: slack: plugin: dump source: my-deb.deb source-type: deb after: - desktop-gtk3 stage-packages: - libasound2 - libnotify4 - libnspr4 - libnss3 - libpcre3 - libpulse0 - libxss1 - libxtst6 electron-launch: plugin: dump source: files/ prepare: | chmod +x bin/electron-launch apps: myApp: command: bin/electron-launch $SNAP/usr/lib/myApp/myApp desktop: usr/share/applications/myApp.desktop # Correct the TMPDIR path for Chromium Framework/Electron to ensure # libappindicator has readable resources. environment: TMPDIR: $XDG_RUNTIME_DIR ``` -------------------------------- ### Building Snap package; Shell Source: https://github.com/discord/electron/blob/main/docs/tutorial/snapcraft.md Executes the `snapcraft` command in the terminal to build the Snap package based on the `snapcraft.yaml` configuration in the project directory. This process fetches sources, builds parts, and creates the `.snap` file. ```sh $ snapcraft Snapped electron-packager-hello-world_0.1_amd64.snap ``` -------------------------------- ### Packaging Distributable Zip Source: https://github.com/discord/electron/blob/main/docs/development/build-instructions-gn.md Uses the Ninja build system to execute the 'electron:electron_dist_zip' target within the 'out/Release' build directory, which packages the built Electron distribution into a zip file. ```sh ninja -C out/Release electron:electron_dist_zip ``` -------------------------------- ### Installing Electron-compatible ChromeDriver for WebDriverJs (sh) Source: https://github.com/discord/electron/blob/main/docs/tutorial/using-selenium-and-webdriver.md Command to install the `electron-chromedriver` npm package, which provides a ChromeDriver binary specifically built for Electron versions. This is a prerequisite for using `selenium-webdriver` with Electron. ```sh npm install electron-chromedriver ``` -------------------------------- ### Initializing Electron Main Process with Destructuring JavaScript Source: https://github.com/discord/electron/blob/main/docs/api/synopsis.md Shows how to require specific modules (`app`, `BrowserWindow`) from the `electron` package using JavaScript destructuring assignment. The script initializes an Electron app, waits for readiness, creates a new browser window, and loads a URL. ```javascript const { app, BrowserWindow } = require('electron') let win app.whenReady().then(() => { win = new BrowserWindow() win.loadURL('https://github.com') }) ```