### Example package.json Source: https://www.electronjs.org/docs/latest/tutorial/tutorial-first-app Shows the structure of a package.json file after initializing the project and installing Electron. Includes name, version, description, main entry point, scripts, author, license, and devDependencies. ```json { "name": "my-electron-app", "version": "1.0.0", "description": "Hello World!", "main": "main.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "Jane Doe", "license": "MIT", "devDependencies": { "electron": "23.1.3" } } ``` -------------------------------- ### Install the Snap Package Source: https://www.electronjs.org/docs/latest/tutorial/snapcraft Install the built snap package using `snap install`. The `--dangerous` flag is required for locally built snaps. ```bash sudo snap install electron-packager-hello-world_0.1_amd64.snap --dangerous ``` -------------------------------- ### Example Packaged Application Structure Source: https://www.electronjs.org/docs/latest/tutorial/snapcraft This is an example of the expected output structure after packaging an Electron application. ```bash . └── dist └── app-linux-x64 ├── LICENSE ├── LICENSES.chromium.html ├── content_shell.pak ├── app ├── icudtl.dat ├── libgcrypt.so.11 ├── libnode.so ├── locales ├── resources ├── v8_context_snapshot.bin └── version ``` -------------------------------- ### Install electron-installer-snap Source: https://www.electronjs.org/docs/latest/tutorial/snapcraft Install the `electron-installer-snap` module as a development dependency. ```bash npm install --save-dev electron-installer-snap ``` -------------------------------- ### Electron Usage Example for C++ Linux Addon Source: https://www.electronjs.org/docs/latest/tutorial/native-code-and-electron-cpp-linux This example demonstrates how to import and use the C++ native addon within your Electron application. It shows basic function calls, event listener setup for 'todo' events, and launching the native GUI. ```javascript // In your Electron main process or renderer process import cppLinux from 'cpp-linux' // Test the basic functionality console.log(cppLinux.helloWorld('Hi!')) // Output: "Hello from C++! You said: Hi!" // Set up event listeners for GTK GUI interactions cppLinux.on('todoAdded', (todo) => { console.log('New todo added:', todo) // todo: { id: "uuid-string", text: "Todo text", date: Date object } }) cppLinux.on('todoUpdated', (todo) => { console.log('Todo updated:', todo) }) cppLinux.on('todoDeleted', (todo) => { console.log('Todo deleted:', todo) }) // Launch the native GTK GUI cppLinux.helloGui() ``` -------------------------------- ### Start and Stop Screen Capture in Renderer Process Source: https://www.electronjs.org/docs/latest/api/desktop-capturer This example shows how to initiate and stop screen capture in the renderer process using `navigator.mediaDevices.getDisplayMedia`. It attaches event listeners to start and stop buttons to control the video stream displayed in a video element. Note that `deviceId` cannot be used for source selection with `getDisplayMedia`. ```javascript // renderer.js const startButton = document.getElementById('startButton') const stopButton = document.getElementById('stopButton') const video = document.querySelector('video') startButton.addEventListener('click', () => { navigator.mediaDevices.getDisplayMedia({ audio: true, video: { width: 320, height: 240, frameRate: 30 } }).then(stream => { video.srcObject = stream video.onloadedmetadata = (e) => video.play() }).catch(e => console.log(e)) }) stopButton.addEventListener('click', () => { video.pause() }) ``` -------------------------------- ### Markdown Example: Quick Start Structure Source: https://www.electronjs.org/docs/latest/development/style-guide Illustrates the expected heading structure for a typical Electron documentation page, including main title, chapters, and sub-chapters. ```markdown # Quick Start ... ## Main process ... ## Renderer process ... ## Run your app ... ### Run as a distribution ... ### Manually downloaded Electron binary ... ``` -------------------------------- ### Install Electron Alpha and Beta Prereleases Source: https://www.electronjs.org/docs/latest/tutorial/installation Install experimental alpha or beta builds of Electron for the next major version. ```bash npm install electron@alpha --save-dev ``` ```bash npm install electron@beta --save-dev ``` -------------------------------- ### Start and Stop Tracing - Electron Source: https://www.electronjs.org/docs/latest/api/content-tracing This snippet demonstrates how to start tracing with all categories included and then stop recording after a delay, saving the trace data to a file. Ensure the `app.whenReady()` event is handled before starting. ```javascript const { app, contentTracing } = require('electron') app.whenReady().then(() => { (async () => { await contentTracing.startRecording({ included_categories: ['*'] }) console.log('Tracing started') await new Promise(resolve => setTimeout(resolve, 5000)) const path = await contentTracing.stopRecording() console.log('Tracing data recorded to ' + path) })() }) ``` -------------------------------- ### macOS Output Structure Example Source: https://www.electronjs.org/docs/latest/tutorial/tutorial-packaging An example of the directory structure created in the 'out' folder after running the 'make' command on macOS, showing packaged app and zip distributable. ```bash out/ ├── out/make/zip/darwin/x64/my-electron-app-darwin-x64-1.0.0.zip ├── ... └── out/my-electron-app-darwin-x64/my-electron-app.app/Contents/MacOS/my-electron-app ``` -------------------------------- ### Install electron-windows-store CLI Source: https://www.electronjs.org/docs/latest/tutorial/windows-store-guide Install the `electron-windows-store` command-line interface globally using npm. This tool is required for packaging Electron applications. ```bash npm install -g electron-windows-store ``` -------------------------------- ### Install Electron Build Tools Source: https://www.electronjs.org/docs/latest/development/build-instructions-gn Installs the Electron Build Tools globally using npm. This package automates much of the setup for compiling Electron from source. ```bash npm install -g @electron/build-tools ``` -------------------------------- ### Main Process: Setup and IPC Listener Source: https://www.electronjs.org/docs/latest/tutorial/context-menu Sets up the main window, defines a context menu template, and listens for 'context-menu' IPC messages from the renderer to display the menu. ```javascript const { app, BrowserWindow, ipcMain, Menu } = require('electron/main') const path = require('node:path') function createWindow () { const mainWindow = new BrowserWindow({ webPreferences: { preload: path.join(__dirname, 'preload.js') } }) mainWindow.loadFile('index.html') const menu = Menu.buildFromTemplate([ { role: 'copy' }, { role: 'cut' }, { role: 'paste' }, { role: 'selectall' } ]) ipcMain.on('context-menu', (event) => { menu.popup({ window: BrowserWindow.fromWebContents(event.sender) }) }) } app.whenReady().then(() => { createWindow() app.on('activate', function () { if (BrowserWindow.getAllWindows().length === 0) createWindow() }) }) app.on('window-all-closed', function () { if (process.platform !== 'darwin') app.quit() }) ``` -------------------------------- ### Install Xcode Command Line Tools Source: https://www.electronjs.org/docs/latest/tutorial/native-code-and-electron On macOS, install the Xcode Command Line Tools to get the necessary compilers and build tools for native Node.js addons. ```shell xcode-select --install ``` -------------------------------- ### Full Renderer Process Notification Example Source: https://www.electronjs.org/docs/latest/tutorial/notifications A complete Electron application example for displaying notifications from the renderer process. This includes the main process setup, HTML structure, and the renderer script. ```javascript const { app, BrowserWindow } = require('electron/main') function createWindow () { const win = new BrowserWindow({ width: 800, height: 600 }) win.loadFile('index.html') } app.whenReady().then(createWindow) app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit() } }) app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) { createWindow() } }) ``` ```html Hello World!

Hello World!

After launching this application, you should see the system notification.

Click it to see the effect in this interface.

``` ```javascript const NOTIFICATION_TITLE = 'Title' const NOTIFICATION_BODY = 'Notification from the Renderer process. Click to log to console.' const CLICK_MESSAGE = 'Notification clicked!' new window.Notification(NOTIFICATION_TITLE, { body: NOTIFICATION_BODY }) .onclick = () => { document.getElementById('output').innerText = CLICK_MESSAGE } ``` -------------------------------- ### Run electron-installer-snap Source: https://www.electronjs.org/docs/latest/tutorial/snapcraft Execute `electron-installer-snap` with the source directory of your packaged application. Ensure `snapcraft` is in your PATH. ```bash npx electron-installer-snap --src=out/myappname-linux-x64 ``` -------------------------------- ### NetLog API Usage Source: https://www.electronjs.org/docs/latest/api/net-log Example demonstrating how to use the netLog API to start and stop network logging within an Electron application. ```APIDOC ## NetLog API Usage Example ### Description This example shows how to initiate network logging using `netLog.startLogging` and then stop it using `netLog.stopLogging` after some network activity has occurred. The path where the logs are saved is then logged to the console. ### Code ```javascript const { app, netLog } = require('electron') app.whenReady().then(async () => { await netLog.startLogging('/path/to/net-log') // After some network events const path = await netLog.stopLogging() console.log('Net-logs written to', path) }) ``` ### Note All methods unless specified can only be used after the `ready` event of the `app` module gets emitted. ``` -------------------------------- ### Create Project Directories Source: https://www.electronjs.org/docs/latest/tutorial/native-code-and-electron Sets up the necessary directory structure for a native addon project. Ensure these directories exist before compiling. ```bash mkdir src mkdir include mkdir js ``` -------------------------------- ### Flash Window Frame Source: https://www.electronjs.org/docs/latest/api/browser-window Starts or stops flashing the window to get the user's attention. On macOS, this flashes the dock icon. ```javascript win.flashFrame(true) ``` -------------------------------- ### Capture screen in Main Process Source: https://www.electronjs.org/docs/latest/api/desktop-capturer This example demonstrates how to set up a request handler in the main process to capture video from a desktop screen. It uses `desktopCapturer.getSources` to find available screens and then provides the first one to the callback. Ensure `useSystemPicker` is set to `true` to allow the system's media picker to be used. ```javascript // main.js const { app, BrowserWindow, desktopCapturer, session } = require('electron') app.whenReady().then(() => { const mainWindow = new BrowserWindow() session.defaultSession.setDisplayMediaRequestHandler((request, callback) => { desktopCapturer.getSources({ types: ['screen'] }).then((sources) => { // Grant access to the first screen found. callback({ video: sources[0], audio: 'loopback' }) }) // If true, use the system picker if available. // Note: this is currently experimental. If the system picker // is available, it will be used and the media request handler // will not be invoked. }, { useSystemPicker: true }) mainWindow.loadFile('index.html') }) ``` -------------------------------- ### Create and Control BrowserView Source: https://www.electronjs.org/docs/latest/api/browser-view This example demonstrates how to create a BrowserWindow, instantiate a BrowserView, set its bounds, and load a URL into it. Ensure the app is ready before creating windows and views. ```javascript const { app, BrowserView, BrowserWindow } = require('electron') app.whenReady().then(() => { const win = new BrowserWindow({ width: 800, height: 600 }) const view = new BrowserView() win.setBrowserView(view) view.setBounds({ x: 0, y: 0, width: 300, height: 300 }) view.webContents.loadURL('https://electronjs.org') }) ``` -------------------------------- ### Run ChromeDriver Server Source: https://www.electronjs.org/docs/latest/tutorial/automated-testing Start the ChromeDriver server after installing `electron-chromedriver`. Note the port number (default is 9515) as it will be used for Selenium connections. ```bash ./node_modules/.bin/chromedriver Starting ChromeDriver (v2.10.291558) on port 9515 Only local connections are allowed. ``` -------------------------------- ### Initialize npm Project with npm Source: https://www.electronjs.org/docs/latest/tutorial/tutorial-first-app Creates a new project folder and initializes an npm package. Sets the entry point to main.js. ```bash mkdir my-electron-app && cd my-electron-app npm init ``` -------------------------------- ### Package.json Scripts for Forge Source: https://www.electronjs.org/docs/latest/tutorial/tutorial-packaging Example of the 'scripts' section in package.json after importing a project into Electron Forge, enabling commands like 'start', 'package', and 'make'. ```json "scripts": { "start": "electron-forge start", "package": "electron-forge package", "make": "electron-forge make" }, ``` -------------------------------- ### Initialize WebdriverIO Project with npm Source: https://www.electronjs.org/docs/latest/tutorial/automated-testing Use this command to initialize a new WebdriverIO project and start the configuration wizard. Ensure you select 'Desktop Testing - of Electron Applications' when prompted. ```bash npm init wdio@latest ./ ``` -------------------------------- ### Main Process: Tray Icon and Context Menu Setup Source: https://www.electronjs.org/docs/latest/tutorial/tray This snippet shows the main process code for creating a tray icon, defining its context menu, and handling user interactions with menu items. It includes logic for creating windows, changing the tray icon image, and setting a title. ```javascript const { app, BrowserWindow, Menu, Tray } = require('electron/main') const { nativeImage } = require('electron/common') let tray = null function createWindow () { const mainWindow = new BrowserWindow() mainWindow.loadFile('index.html') } app.whenReady().then(() => { createWindow() const red = nativeImage.createFromDataURL('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAACTSURBVHgBpZKBCYAgEEV/TeAIjuIIbdQIuUGt0CS1gW1iZ2jIVaTnhw+Cvs8/OYDJA4Y8kR3ZR2/kmazxJbpUEfQ/Dm/UG7wVwHkjlQdMFfDdJMFaACebnjJGyDWgcnZu1/lrCrl6NCoEHJBrDwEr5NrT6ko/UV8xdLAC2N49mlc5CylpYh8wCwqrvbBGLoKGvz8Bfq0QPWEUo/EAAAAASUVORK5CYII=') const green = nativeImage.createFromDataURL('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUCOSURBVHgBpZLRDYAgEEOrEzgCozCCGzkCbKArOIlugJvgoRAUNcLRpvGH19TkgFQWkqIohhK8UEaKwKcsOg/+WR1vX+AlA74u6q4FqgCOSzwsGHCwbKliAF89Cv89tWmOT4VaVMoVbOBrdQUz+FrD6XItzh4LzYB1HFJ9yrEkZ4l+wvcid9pTssh4UKbPd+4vED2Nd54iAAAAAElFTkSuQmCC') tray = new Tray(red) tray.setToolTip('Tray Icon Demo') const contextMenu = Menu.buildFromTemplate([ { label: 'Open App', click: () => { const wins = BrowserWindow.getAllWindows() if (wins.length === 0) { createWindow() } else { wins[0].focus() } } }, { label: 'Set Green Icon', type: 'checkbox', click: ({ checked }) => { checked ? tray.setImage(green) : tray.setImage(red) } }, { label: 'Set Title', type: 'checkbox', click: ({ checked }) => { checked ? tray.setTitle('Title') : tray.setTitle('') } }, { role: 'quit' } ]) tray.setContextMenu(contextMenu) }) app.on('window-all-closed', function () { }) app.on('activate', function () { if (BrowserWindow.getAllWindows().length === 0) createWindow() }) ``` -------------------------------- ### Main Process Setup for IPC Source: https://www.electronjs.org/docs/latest/tutorial/ipc Sets up the main process with window creation, IPC listeners, and a custom menu that sends messages to the renderer. Requires `preload.js` for exposing IPC functionality. ```javascript const { app, BrowserWindow, Menu, ipcMain } = require('electron/main') const path = require('node:path') function createWindow () { const mainWindow = new BrowserWindow({ webPreferences: { preload: path.join(__dirname, 'preload.js') } }) const menu = Menu.buildFromTemplate([ { label: app.name, submenu: [ { click: () => mainWindow.webContents.send('update-counter', 1), label: 'Increment' }, { click: () => mainWindow.webContents.send('update-counter', -1), label: 'Decrement' } ] } ]) Menu.setApplicationMenu(menu) mainWindow.loadFile('index.html') // Open the DevTools. mainWindow.webContents.openDevTools() } app.whenReady().then(() => { ipcMain.on('counter-value', (_event, value) => { console.log(value) // will print value to Node console }) createWindow() app.on('activate', function () { if (BrowserWindow.getAllWindows().length === 0) createWindow() }) }) app.on('window-all-closed', function () { if (process.platform !== 'darwin') app.quit() }) ``` -------------------------------- ### Create Electron App with create-electron-app Source: https://www.electronjs.org/docs/latest/tutorial/snapcraft Initialize a new Electron application project using `create-electron-app`. ```bash $ npx create-electron-app@latest my-app ``` -------------------------------- ### Basic Electron Window Setup Source: https://www.electronjs.org/docs/latest/tutorial/keyboard-shortcuts This is the main process code for setting up a basic Electron application window. It handles application lifecycle events and loads an HTML file. ```javascript // Modules to control application life and create native browser window const { app, BrowserWindow } = require('electron/main') function createWindow () { // Create the browser window. const mainWindow = new BrowserWindow({ width: 800, height: 600 }) // and load the index.html of the app. mainWindow.loadFile('index.html') } // This method will be called when Electron has finished // initialization and is ready to create browser windows. // Some APIs can only be used after this event occurs. app.whenReady().then(() => { createWindow() app.on('activate', function () { // On macOS it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (BrowserWindow.getAllWindows().length === 0) createWindow() }) }) // Quit when all windows are closed, except on macOS. There, it's common // for applications and their menu bar to stay active until the user quits // explicitly with Cmd + Q. app.on('window-all-closed', function () { if (process.platform !== 'darwin') app.quit() }) ``` -------------------------------- ### Adjust Selection Example Source: https://www.electronjs.org/docs/latest/api/web-contents Demonstrates how to adjust the start and end points of a text selection in a web page. Use negative values to move towards the beginning and positive values towards the end. ```javascript const win = new BrowserWindow() // Adjusts the beginning of the selection 1 letter forward, // and the end of the selection 5 letters forward. win.webContents.adjustSelection({ start: 1, end: 5 }) // Adjusts the beginning of the selection 2 letters forward, // and the end of the selection 3 letters backward. win.webContents.adjustSelection({ start: 2, end: -3 }) ``` -------------------------------- ### Set PowerShell Execution Policy Source: https://www.electronjs.org/docs/latest/tutorial/windows-store-guide Before running the Desktop App Converter installation script, ensure your system's execution policy allows running scripts by setting it to bypass. This is a one-time setup. ```powershell Set-ExecutionPolicy bypass ``` -------------------------------- ### Flash Taskbar Button Source: https://www.electronjs.org/docs/latest/tutorial/windows-taskbar Call `flashFrame(true)` to highlight the taskbar button and get the user's attention. Remember to call `flashFrame(false)` to disable the flashing, for example, when the window gains focus or after a timeout. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() win.once('focus', () => win.flashFrame(false)) win.flashFrame(true) ``` -------------------------------- ### Win32 GUI Initialization and Window Creation Source: https://www.electronjs.org/docs/latest/tutorial/native-code-and-electron-cpp-win32 Sets up the Win32 GUI environment, registers a window class, and creates the main application window. Ensures DPI awareness for scalable UI elements. ```cpp void hello_gui() { // Launch GUI in a separate thread std::thread guiThread([]() { // Enable Per-Monitor DPI awareness SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); // Initialize Common Controls INITCOMMONCONTROLSEX icex; icex.dwSize = sizeof(INITCOMMONCONTROLSEX); icex.dwICC = ICC_STANDARD_CLASSES | ICC_WIN95_CLASSES; InitCommonControlsEx(&icex); // Register window class WNDCLASSEXW wc = {}; wc.cbSize = sizeof(WNDCLASSEXW); wc.lpfnWndProc = WindowProc; wc.hInstance = GetModuleHandle(nullptr); wc.lpszClassName = L"TodoApp"; RegisterClassExW(&wc); // Get the DPI for the monitor UINT dpi = GetDpiForSystem(); // Create window HWND hwnd = CreateWindowExW( 0, L"TodoApp", L"Todo List", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, Scale(500, dpi), Scale(500, dpi), nullptr, nullptr, GetModuleHandle(nullptr), nullptr ); if (hwnd == nullptr) { return; } // Create the modern font with DPI-aware size HFONT hFont = CreateFontW( -Scale(14, dpi), // Height (scaled) 0, // Width 0, // Escapement 0, // Orientation FW_NORMAL, // Weight FALSE, // Italic FALSE, // Underline FALSE, // StrikeOut DEFAULT_CHARSET, // CharSet OUT_DEFAULT_PRECIS, // OutPrecision CLIP_DEFAULT_PRECIS, // ClipPrecision CLEARTYPE_QUALITY, // Quality DEFAULT_PITCH | FF_DONTCARE, // Pitch and Family L"Segoe UI" // Font face name ); // Create input controls with scaled positions and sizes HWND hEdit = CreateWindowExW(0, WC_EDITW, L"", WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL, Scale(10, dpi), Scale(10, dpi), Scale(250, dpi), Scale(25, dpi), hwnd, (HMENU)1, GetModuleHandle(nullptr), nullptr); SendMessageW(hEdit, WM_SETFONT, (WPARAM)hFont, TRUE); // Create date picker HWND hDatePicker = CreateWindowExW(0, DATETIMEPICK_CLASSW, L"", WS_CHILD | WS_VISIBLE | DTS_SHORTDATECENTURYFORMAT, Scale(270, dpi), Scale(10, dpi), Scale(100, dpi), Scale(25, dpi), hwnd, (HMENU)4, GetModuleHandle(nullptr), nullptr); SendMessageW(hDatePicker, WM_SETFONT, (WPARAM)hFont, TRUE); HWND hButton = CreateWindowExW(0, WC_BUTTONW, L"Add", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, Scale(380, dpi), Scale(10, dpi), Scale(50, dpi), Scale(25, dpi), hwnd, (HMENU)2, GetModuleHandle(nullptr), nullptr); SendMessageW(hButton, WM_SETFONT, (WPARAM)hFont, TRUE); HWND hListBox = CreateWindowExW(0, WC_LISTBOXW, L"", WS_CHILD | WS_VISIBLE | WS_BORDER | WS_VSCROLL | LBS_NOTIFY, Scale(10, dpi), Scale(45, dpi), Scale(460, dpi), Scale(400, dpi), hwnd, (HMENU)3, GetModuleHandle(nullptr), nullptr); SendMessageW(hListBox, WM_SETFONT, (WPARAM)hFont, TRUE); ShowWindow(hwnd, SW_SHOW); // Message loop MSG msg = {}; while (GetMessage(&msg, nullptr, 0, 0)) { TranslateMessage(&msg); ``` -------------------------------- ### Main Process Setup with Preload Script Source: https://www.electronjs.org/docs/latest/tutorial/tutorial-preload This code sets up the main Electron process, creating a BrowserWindow and specifying the path to the preload script in its webPreferences. It handles application lifecycle events. ```javascript const { app, BrowserWindow } = require('electron/main') const path = require('node:path') const createWindow = () => { const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { preload: path.join(__dirname, 'preload.js') } }) win.loadFile('index.html') } app.whenReady().then(() => { createWindow() app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) { createWindow() } }) }) app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit() } }) ``` -------------------------------- ### Sign App with electron-winstaller Source: https://www.electronjs.org/docs/latest/tutorial/code-signing Integrate code signing into the electron-winstaller process for creating Squirrel.Windows installers. This example demonstrates using custom signing parameters and specifying a custom sign tool path. Note the use of `async/await` which requires an async function context. ```javascript const electronInstaller = require('electron-winstaller') // NB: Use this syntax within an async function, Node does not have support for // top-level await as of Node 12. try { await electronInstaller.createWindowsInstaller({ appDirectory: '/tmp/build/my-app-64', outputDirectory: '/tmp/build/installer64', authors: 'My App Inc.', exe: 'myapp.exe', windowsSign: { signWithParams: '--my=custom --parameters', // If signtool.exe does not work for you, customize! signToolPath: 'C:\\Path\\To\\my-custom-tool.exe' } }) console.log('It worked!') } catch (e) { console.log(`No dice: ${e.message}`) } ``` -------------------------------- ### Markdown Example: API Class Structure Source: https://www.electronjs.org/docs/latest/development/style-guide Provides an example of documenting classes, including methods, properties, and events, using 'Session' and 'Cookies' as examples. ```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)` ``` -------------------------------- ### Main Process Setup for IPC Source: https://www.electronjs.org/docs/latest/tutorial/ipc Sets up IPC listeners and the main window. Requires `preload.js` to be loaded. ```javascript const { app, BrowserWindow, ipcMain } = require('electron/main') const path = require('node:path') function handleSetTitle (event, title) { const webContents = event.sender const win = BrowserWindow.fromWebContents(webContents) win.setTitle(title) } function createWindow () { const mainWindow = new BrowserWindow({ webPreferences: { preload: path.join(__dirname, 'preload.js') } }) mainWindow.loadFile('index.html') } app.whenReady().then(() => { ipcMain.on('set-title', handleSetTitle) createWindow() app.on('activate', function () { if (BrowserWindow.getAllWindows().length === 0) createWindow() }) }) app.on('window-all-closed', function () { if (process.platform !== 'darwin') app.quit() }) ``` -------------------------------- ### Manually install Electron binary Source: https://www.electronjs.org/docs/latest/breaking-changes If you need to download the Electron binary on-demand, you can use the `install-electron` script, which replicates the functionality of the former `postinstall` script. ```bash npm install electron --save-dev --ignore-scripts npx install-electron --no ``` -------------------------------- ### Electron Starter Code Source: https://www.electronjs.org/docs/latest/tutorial/custom-title-bar Basic Electron application setup for creating a window. ```javascript const { app, BrowserWindow } = require('electron') function createWindow () { const win = new BrowserWindow({}) win.loadURL('https://example.com') } app.whenReady().then(() => { createWindow() }) ``` -------------------------------- ### Start and Stop Network Logging in Electron Source: https://www.electronjs.org/docs/latest/api/net-log Starts network logging to a specified file path and then stops it, logging the path where the logs were written. Ensure the app is ready before starting logging. ```javascript const { app, netLog } = require('electron') app.whenReady().then(async () => { await netLog.startLogging('/path/to/net-log') // After some network events const path = await netLog.stopLogging() console.log('Net-logs written to', path) }) ``` -------------------------------- ### Install Windows Desktop App Converter Source: https://www.electronjs.org/docs/latest/tutorial/windows-store-guide Install the Desktop App Converter by running its PowerShell script, providing the path to the Windows base image. A reboot may be required after the initial installation. ```powershell .\DesktopAppConverter.ps1 -Setup -BaseImage .\BaseImage-14316.wim ``` -------------------------------- ### Show Dialog for File or Directory Selection Source: https://www.electronjs.org/docs/latest/api/dialog This example demonstrates how to configure the dialog to allow selection of either files or directories. Note that on Windows and Linux, if both 'openFile' and 'openDirectory' are set, a directory selector will be shown. ```javascript dialog.showOpenDialogSync(mainWindow, { properties: ['openFile', 'openDirectory'] }) ``` -------------------------------- ### Electron In-App Purchase Main Process Example Source: https://www.electronjs.org/docs/latest/tutorial/in-app-purchases This example demonstrates how to use the `inAppPurchase` module in the main process to handle in-app purchases. It includes listening for transaction updates, retrieving product information, and initiating purchases. Ensure you listen for 'transactions-updated' as early as possible in your app's lifecycle. ```javascript // Main process const { inAppPurchase } = require('electron') const PRODUCT_IDS = ['id1', 'id2'] // Listen for transactions as soon as possible. inAppPurchase.on('transactions-updated', (event, transactions) => { if (!Array.isArray(transactions)) { return } // Check each transaction. for (const transaction of transactions) { const payment = transaction.payment switch (transaction.transactionState) { case 'purchasing': console.log(`Purchasing ${payment.productIdentifier}...`) break case 'purchased': { console.log(`${payment.productIdentifier} purchased.`) // Get the receipt url. const receiptURL = inAppPurchase.getReceiptURL() console.log(`Receipt URL: ${receiptURL}`) // Submit the receipt file to the server and check if it is valid. // @see https://developer.apple.com/library/content/releasenotes/General/ValidateAppStoreReceipt/Chapters/ValidateRemotely.html // ... // If the receipt is valid, the product is purchased // ... // Finish the transaction. inAppPurchase.finishTransactionByDate(transaction.transactionDate) break } case 'failed': console.log(`Failed to purchase ${payment.productIdentifier}.`) // Finish the transaction. inAppPurchase.finishTransactionByDate(transaction.transactionDate) break case 'restored': console.log(`The purchase of ${payment.productIdentifier} has been restored.`) break case 'deferred': console.log(`The purchase of ${payment.productIdentifier} has been deferred.`) break default: break } } }) // Check if the user is allowed to make in-app purchase. if (!inAppPurchase.canMakePayments()) { console.log('The user is not allowed to make in-app purchase.') } // Retrieve and display the product descriptions. inAppPurchase.getProducts(PRODUCT_IDS).then(products => { // Check the parameters. if (!Array.isArray(products) || products.length <= 0) { console.log('Unable to retrieve the product information.') return } // Display the name and price of each product. for (const product of products) { console.log(`The price of ${product.localizedTitle} is ${product.formattedPrice}.`) } // Ask the user which product they want to purchase. const selectedProduct = products[0] const selectedQuantity = 1 // Purchase the selected product. inAppPurchase.purchaseProduct(selectedProduct.productIdentifier, selectedQuantity).then(isProductValid => { if (!isProductValid) { console.log('The product is not valid.') return } console.log('The payment has been added to the payment queue.') }) }) ``` -------------------------------- ### Install update-electron-app with Yarn Source: https://www.electronjs.org/docs/latest/tutorial/tutorial-publishing-updating Install the `update-electron-app` module as a runtime dependency using Yarn. ```bash yarn add update-electron-app ``` -------------------------------- ### Install update-electron-app with npm Source: https://www.electronjs.org/docs/latest/tutorial/tutorial-publishing-updating Install the `update-electron-app` module as a runtime dependency using npm. ```bash npm install update-electron-app ``` -------------------------------- ### Debugger Usage Example Source: https://www.electronjs.org/docs/latest/api/debugger Example demonstrating how to attach, send commands, and handle events for the Debugger. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() try { win.webContents.debugger.attach('1.1') } catch (err) { console.log('Debugger attach failed : ', err) } win.webContents.debugger.on('detach', (event, reason) => { console.log('Debugger detached due to : ', reason) }) win.webContents.debugger.on('message', (event, method, params) => { if (method === 'Network.requestWillBeSent') { if (params.request.url === 'https://www.github.com') { win.webContents.debugger.detach() } } }) win.webContents.debugger.sendCommand('Network.enable') ``` -------------------------------- ### Main Process: Electron App Setup and Theme Handling Source: https://www.electronjs.org/docs/latest/tutorial/dark-mode Sets up the main Electron window and handles IPC messages for toggling and resetting the dark mode theme. This script requires the 'electron/main' module. ```javascript const { app, BrowserWindow, ipcMain, nativeTheme } = require('electron/main') const path = require('node:path') function createWindow () { const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { preload: path.join(__dirname, 'preload.js') } }) win.loadFile('index.html') } ipcMain.handle('dark-mode:toggle', () => { if (nativeTheme.shouldUseDarkColors) { nativeTheme.themeSource = 'light' } else { nativeTheme.themeSource = 'dark' } return nativeTheme.shouldUseDarkColors }) ipcMain.handle('dark-mode:system', () => { nativeTheme.themeSource = 'system' }) app.whenReady().then(() => { createWindow() app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) { createWindow() } }) }) app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit() } }) ``` -------------------------------- ### HTML for Protocol Demo Source: https://www.electronjs.org/docs/latest/tutorial/launch-app-from-url-in-another-app This HTML sets up a basic page with links and buttons to demonstrate launching the app via a custom URL protocol. It includes a link that uses the 'electron-fiddle://' scheme. ```html app.setAsDefaultProtocol Demo

App Default Protocol Demo

The protocol API allows us to register a custom protocol and intercept existing protocol requests.

These methods allow you to set and unset the protocols your app should be the default app for. Similar to when a browser asks to be your default for viewing web pages.

Open the full protocol API documentation in your browser.

-----

Demo

First: Launch current page in browser

Then: Launch the app from a web link! Click here to launch the app

----

You can set your app as the default app to open for a specific protocol. For instance, in this demo we set this app as the default for electron-fiddle://. The demo button above will launch a page in your default browser with a link. Click that link and it will re-launch this app.

Packaging

This feature will only work on macOS when your app is packaged. It will not work when you're launching it in development from the command-line. When you package your app you'll need to make sure the macOS plist for the app is updated to include the new protocol handler. If you're using @electron/packager then you can add the flag --extend-info with a path to the plist you've created. The one for this app is below:

macOS plist

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
            <plist version="1.0">
                <dict>
                    <key>CFBundleURLTypes</key>
                    <array>
                        <dict>
                            <key>CFBundleURLSchemes</key>
                            <array>
                                <string>electron-api-demos</string>
                            </array>
                            <key>CFBundleURLName</key>
                            <string>Electron API Demos Protocol</string>
                        </dict>
                    </array>
                    <key>ElectronTeamID</key>
                    <string>VEKTX9H2N7</string>
                </dict>
            </plist>
        
    

``` -------------------------------- ### Content Security Policy Examples Source: https://www.electronjs.org/docs/latest/tutorial/security Illustrates examples of Content Security Policy (CSP) headers. The 'Good' example restricts script sources to the current origin and a specific API domain, enhancing security against injection attacks. ```http // Bad Content-Security-Policy: '*' // Good Content-Security-Policy: script-src 'self' https://apis.example.com ``` -------------------------------- ### Full Main Process Notification Example Source: https://www.electronjs.org/docs/latest/tutorial/notifications A complete Electron application example demonstrating how to show a notification from the main process. This includes setting up the main window and triggering the notification. ```javascript const { app, BrowserWindow, Notification } = require('electron/main') function createWindow () { const win = new BrowserWindow({ width: 800, height: 600 }) win.loadFile('index.html') } const NOTIFICATION_TITLE = 'Basic Notification' const NOTIFICATION_BODY = 'Notification from the Main process' function showNotification () { new Notification({ title: NOTIFICATION_TITLE, body: NOTIFICATION_BODY }).show() } app.whenReady().then(createWindow).then(showNotification) app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit() } }) app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) { createWindow() } }) ``` ```html Hello World!

Hello World!

After launching this application, you should see the system notification.

``` -------------------------------- ### Install update-electron-app with Yarn Source: https://www.electronjs.org/docs/latest/tutorial/updates Installs the update-electron-app module using Yarn, an alternative Node.js package manager. ```bash yarn add update-electron-app ``` -------------------------------- ### Initialize Win32 Window and Message Loop Source: https://www.electronjs.org/docs/latest/tutorial/native-code-and-electron-cpp-win32 Sets up the necessary Win32 window class, creates the main window, and enters the message loop for handling window events. This forms the foundation for the GUI. ```cpp INITCOMMONCONTROLSEX icex; icex.dwSize = sizeof(INITCOMMONCONTROLSEX); icex.dwICC = ICC_STANDARD_CLASSES | ICC_WIN95_CLASSES; InitCommonControlsEx(&icex); // Register window class WNDCLASSEXW wc = {}; wc.cbSize = sizeof(WNDCLASSEXW); wc.lpfnWndProc = WindowProc; wc.hInstance = GetModuleHandle(nullptr); wc.lpszClassName = L"TodoApp"; RegisterClassExW(&wc); // Get the DPI for the monitor UINT dpi = GetDpiForSystem(); // Create window HWND hwnd = CreateWindowExW( 0, L"TodoApp", L"Todo List", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, Scale(500, dpi), Scale(500, dpi), nullptr, nullptr, GetModuleHandle(nullptr), nullptr ); if (hwnd == nullptr) { return; } // Controls go here! The window is currently empty, // we'll add controls in the next step. ShowWindow(hwnd, SW_SHOW); // Message loop MSG msg = {}; while (GetMessage(&msg, nullptr, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } // Clean up DeleteObject(hFont); }); // Detach the thread so it runs independently guiThread.detach(); } ``` -------------------------------- ### Install update-electron-app with npm Source: https://www.electronjs.org/docs/latest/tutorial/updates Installs the update-electron-app module using npm, a convenient Node.js package manager. ```bash npm install update-electron-app ``` -------------------------------- ### Install GTK3 Development Files (Fedora/RHEL/CentOS) Source: https://www.electronjs.org/docs/latest/tutorial/native-code-and-electron-cpp-linux Installs necessary packages for GTK3 development on Fedora/RHEL/CentOS systems. ```bash sudo dnf install gcc-c++ pkgconfig gtk3-devel ``` -------------------------------- ### Create and Open Electron App Source: https://www.electronjs.org/docs/latest/tutorial/debugging-vscode Use these commands to create a new Electron app and open it in VSCode. This is the initial setup step for debugging. ```bash $ npx create-electron-app@latest my-app $ code my-app ``` -------------------------------- ### Install GTK3 Development Files (Ubuntu/Debian) Source: https://www.electronjs.org/docs/latest/tutorial/native-code-and-electron-cpp-linux Installs necessary packages for GTK3 development on Ubuntu/Debian systems. ```bash sudo apt-get install build-essential pkg-config libgtk-3-dev ``` -------------------------------- ### Programmatic Usage of electron-installer-snap Source: https://www.electronjs.org/docs/latest/tutorial/snapcraft Use `electron-installer-snap` programmatically within your build pipeline. This example shows a basic Promise-based invocation. ```javascript const snap = require('electron-installer-snap') snap(options) .then(snapPath => console.log(`Created snap at ${snapPath}!`)) ```