### Electron Launch Script Example Source: https://github.com/itsidorkin28/sid-electron/blob/main/docs/tutorial/snapcraft.md This is an example of an electron-launch script used to execute the application binary. It passes arguments and sets environment variables for proper execution. ```sh #!/bin/sh exec "$@" --executed-from="$(pwd)" --pid=$$ > /dev/null 2>&1 & ``` -------------------------------- ### Install WebdriverIO Starter Toolkit Source: https://github.com/itsidorkin28/sid-electron/blob/main/docs/tutorial/automated-testing.md Installs the WebdriverIO starter toolkit to set up a new testing environment for Electron applications. This command initiates a configuration wizard that guides users through package installation and generates a `wdio.conf.js` file. ```sh npm init wdio@latest ./ ``` -------------------------------- ### Example package.json for Electron App Source: https://github.com/itsidorkin28/sid-electron/blob/main/docs/tutorial/tutorial-2-first-app.md Illustrates the structure of a package.json file after initializing an npm project and installing Electron. Key fields include 'name', 'version', 'description', 'main' (entry point, e.g., 'main.js'), 'scripts', 'author', 'license', and 'devDependencies' which lists 'electron' with its version. ```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 electron-windows-store CLI Source: https://github.com/itsidorkin28/sid-electron/blob/main/docs/tutorial/windows-store-guide.md Installs the `electron-windows-store` command-line interface globally using npm. This tool is essential for packaging Electron applications into the `.appx` format. ```sh npm install -g electron-windows-store ``` -------------------------------- ### Run Snap Application Source: https://github.com/itsidorkin28/sid-electron/blob/main/docs/tutorial/snapcraft.md Executes an installed snap application by calling its name. This command assumes the snap application's name is 'electron-packager-hello-world'. ```sh electron-packager-hello-world ``` -------------------------------- ### Start Electron app using npm Source: https://github.com/itsidorkin28/sid-electron/blob/main/docs/tutorial/tutorial-2-first-app.md Command to execute the Electron application using npm, which triggers the 'start' script defined in package.json. ```sh npm run start ``` -------------------------------- ### Install Snap Package Source: https://github.com/itsidorkin28/sid-electron/blob/main/docs/tutorial/snapcraft.md Installs a locally built snap package using the snap install command with the --dangerous flag. This is typically used for installing snap packages that have not been signed by a known publisher. ```sh sudo snap install electron-packager-hello-world_0.1_amd64.snap --dangerous ``` -------------------------------- ### Set Up Auto Updater with Electron Source: https://context7.com/itsidorkin28/sid-electron/llms.txt This example shows how to configure and manage automatic application updates using the `electron-updater` module. It covers setting the update feed URL, checking for updates, handling various update events (checking, available, downloaded, error), and prompting the user to install the update. ```javascript const { autoUpdater } = require('electron-updater') const { app, dialog } = require('electron') // Configure update server autoUpdater.setFeedURL({ provider: 'github', owner: 'your-username', repo: 'your-repo' }) // Check for updates autoUpdater.checkForUpdatesAndNotify() // Update events autoUpdater.on('checking-for-update', () => { console.log('Checking for updates...') }) autoUpdater.on('update-available', (info) => { console.log('Update available:', info.version) }) autoUpdater.on('update-not-available', () => { console.log('App is up to date') }) autoUpdater.on('download-progress', (progress) => { mainWindow.setProgressBar(progress.percent / 100) }) autoUpdater.on('update-downloaded', (info) => { mainWindow.setProgressBar(-1) dialog.showMessageBox({ type: 'info', title: 'Update Ready', message: `Version ${info.version} is ready to install.`, buttons: ['Install Now', 'Later'] }).then(result => { if (result.response === 0) { autoUpdater.quitAndInstall() } }) }) autoUpdater.on('error', (error) => { console.error('Update error:', error) }) ``` -------------------------------- ### Install electron-installer-snap Source: https://github.com/itsidorkin28/sid-electron/blob/main/docs/tutorial/snapcraft.md Installs the electron-installer-snap module as a development dependency using npm. This module is used for building snap packages for Electron applications. ```sh npm install --save-dev electron-installer-snap ``` -------------------------------- ### API Reference Title and Description Example Source: https://github.com/itsidorkin28/sid-electron/blob/main/docs/development/style-guide.md Shows the required format for API module documentation titles and one-line descriptions using markdown quotes. ```markdown # session > Manage browser sessions, cookies, cache, proxy settings, etc. ``` -------------------------------- ### Initialize npm Project and Install Electron Source: https://github.com/itsidorkin28/sid-electron/blob/main/docs/tutorial/tutorial-2-first-app.md Scaffolds a new Electron project by initializing an npm package and installing Electron as a development dependency. This involves creating a project folder, running 'npm init' to configure package.json, and then executing 'npm install electron --save-dev'. Ensure that your package manager is configured to use a regular 'node_modules' folder for compatibility with Electron's packaging toolchain. ```sh mkdir my-electron-app && cd my-electron-app npm init npm install electron --save-dev ``` -------------------------------- ### Start Electron Application Source: https://github.com/itsidorkin28/sid-electron/blob/main/docs/development/build-instructions-gn.md Starts the compiled Electron application. This command is used after the Electron binary has been successfully built. The application can also be loaded into Electron Fiddle for testing. ```sh e start ``` -------------------------------- ### Install and Import Electron Forge CLI Source: https://github.com/itsidorkin28/sid-electron/blob/main/docs/tutorial/tutorial-5-packaging.md Installs the Electron Forge CLI as a dev dependency and imports an existing project into Forge's configuration. This sets up your project for packaging and distribution. ```sh npm install --save-dev @electron-forge/cli npx electron-forge import ``` -------------------------------- ### Install Electron using npm Source: https://github.com/itsidorkin28/sid-electron/blob/main/README.md Installs prebuilt Electron binaries as a development dependency in your project using npm. This is the recommended method for integrating Electron into your application. ```sh npm install electron --save-dev ``` -------------------------------- ### Initialize Electron Default App Source: https://github.com/itsidorkin28/sid-electron/blob/main/default_app/index.html This JavaScript code snippet initializes the default application settings for Electron. It's a common step to ensure the application starts with its predefined configurations. No external dependencies are explicitly mentioned for this core initialization function. ```javascript window.electronDefaultApp.initialize() ``` -------------------------------- ### Run Electron Ad-hoc with npx Source: https://github.com/itsidorkin28/sid-electron/blob/main/docs/tutorial/installation.md Runs the current working directory with Electron using the npx command runner. This method is useful for quick testing without a formal npm installation, but dependencies will not be installed. ```sh npx electron . ``` -------------------------------- ### Fiddle Example: WebHID API Source: https://github.com/itsidorkin28/sid-electron/blob/main/docs/tutorial/devices.md This fiddle example demonstrates the WebHID API in Electron, focusing on device selection via `setDevicePermissionHandler` and the `select-hid-device` event. ```javascript console.log('Running WebHID Fiddle'); // Fiddle code would go here ``` -------------------------------- ### Verify Node.js and npm Installation (Shell) Source: https://github.com/itsidorkin28/sid-electron/blob/main/docs/tutorial/tutorial-1-prerequisites.md This command checks if Node.js and npm have been installed correctly by displaying their respective versions. This is a crucial first step in setting up the development environment for Electron applications. ```sh $ node -v v16.14.2 $ npm -v 8.7.0 ``` -------------------------------- ### Install Electron Build Tools Globally Source: https://github.com/itsidorkin28/sid-electron/blob/main/docs/development/build-instructions-gn.md Installs the recommended Electron Build Tools globally using npm. This makes the `e` command available for managing Electron source code and builds. ```sh npm install -g @electron/build-tools ``` -------------------------------- ### Get Tray Icon GUID (macOS, Windows) Source: https://github.com/itsidorkin28/sid-electron/blob/main/docs/api/tray.md Retrieves the GUID used to uniquely identify the tray icon. This allows the icon to retain its position between application relaunches. Returns null if no GUID is set. ```javascript const guid = tray.getGUID(); ``` -------------------------------- ### macOS Output Example for Packaged App Source: https://github.com/itsidorkin28/sid-electron/blob/main/docs/tutorial/tutorial-5-packaging.md Illustrates the typical output structure after running `npm run make` on macOS. It shows the generated distributable zip file and the packaged application folder. ```text 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 ``` -------------------------------- ### Create Electron Application Distributable Source: https://github.com/itsidorkin28/sid-electron/blob/main/docs/tutorial/tutorial-5-packaging.md Runs the Electron Forge `make` script to package the application code with the Electron binary and then create platform-specific distributables (installers or portable executables). ```sh npm run make ``` -------------------------------- ### Configure Electron main script in package.json Source: https://github.com/itsidorkin28/sid-electron/blob/main/docs/tutorial/tutorial-2-first-app.md Defines the main entry point for an Electron application and sets up a start script to run the app. It requires the 'electron' dev dependency. ```json { "name": "my-electron-app", "version": "1.0.0", "description": "Hello World!", "main": "main.js", "scripts": { "start": "electron .", "test": "echo \"Error: no test specified\" && exit 1" }, "author": "Jane Doe", "license": "MIT", "devDependencies": { "electron": "23.1.3" } } ``` -------------------------------- ### Start Service Worker and Send Messages (JavaScript) Source: https://github.com/itsidorkin28/sid-electron/blob/main/docs/api/service-workers.md This example shows how to start a specific service worker for a given scope and send messages to it. It first collects the scopes of all running workers, then iterates through them to ensure each is started. Once started, it sends a 'window-created' message to the service worker, passing the new window's ID. ```javascript const { app, session } = require('electron') const { serviceWorkers } = session.defaultSession // Collect service workers scopes const workerScopes = Object.values(serviceWorkers.getAllRunning()).map((info) => info.scope) app.on('browser-window-created', async (event, window) => { for (const scope of workerScopes) { try { // Ensure worker is started const serviceWorker = await serviceWorkers.startWorkerForScope(scope) serviceWorker.send('window-created', { windowId: window.id }) } catch (error) { console.error(`Failed to start service worker for ${scope}`) console.error(error) } } }) ``` -------------------------------- ### Install and Run ChromeDriver for Selenium Source: https://github.com/itsidorkin28/sid-electron/blob/main/docs/tutorial/automated-testing.md Installs the `electron-chromedriver` package and starts the ChromeDriver server. This is a prerequisite for using Selenium with Electron, allowing the Selenium bindings to communicate with the Electron browser. ```sh npm install --save-dev electron-chromedriver ./node_modules/.bin/chromedriver Starting ChromeDriver (v2.10.291558) on port 9515 Only local connections are allowed. ``` -------------------------------- ### View Build Tools Help Source: https://github.com/itsidorkin28/sid-electron/blob/main/docs/development/build-instructions-gn.md Displays help information for the Electron Build Tools. Running `e --help` lists all available commands, and using `--help` with a specific command provides detailed usage instructions. ```sh e --help ``` -------------------------------- ### Install Electron Build Tools Source: https://github.com/itsidorkin28/sid-electron/blob/main/CLAUDE.md Installs the essential `@electron/build-tools` package globally, which provides the `e` command for managing Electron development. This tool is crucial for syncing source code, building Electron, and running tests. ```bash npm i -g @electron/build-tools ``` -------------------------------- ### Run electron-installer-snap programmatically Source: https://github.com/itsidorkin28/sid-electron/blob/main/docs/tutorial/snapcraft.md Demonstrates how to use the electron-installer-snap module programmatically within a Node.js script. It takes options 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}!`)) ``` -------------------------------- ### Create a basic Electron main process script Source: https://github.com/itsidorkin28/sid-electron/blob/main/docs/tutorial/tutorial-2-first-app.md A simple JavaScript file that serves as the entry point for an Electron application's main process. It logs a message to the console when executed. ```js console.log('Hello from Electron 👋') ``` -------------------------------- ### Markdown Structure Example Source: https://github.com/itsidorkin28/sid-electron/blob/main/docs/development/style-guide.md Demonstrates the hierarchical heading structure for Electron documentation pages, including main titles, chapters, and sub-chapters. ```markdown # Quick Start ... ## Main process ... ## Renderer process ... ## Run your app ... ### Run as a distribution ... ### Manually downloaded Electron binary ... ``` -------------------------------- ### Build and Set Context Menu (Linux Example) Source: https://github.com/itsidorkin28/sid-electron/blob/main/docs/api/tray.md Example demonstrating how to build a context menu using Electron's Menu module and set it for a tray icon on Linux. It highlights the need to call setContextMenu again if menu items are modified. ```javascript const { app, Menu, Tray } = require('electron'); let appIcon = null; app.whenReady().then(() => { appIcon = new Tray('/path/to/my/icon'); const contextMenu = Menu.buildFromTemplate([ { label: 'Item1', type: 'radio' }, { label: 'Item2', type: 'radio' } ]); // Make a change to the context menu contextMenu.items[1].checked = false; // Call this again for Linux because we modified the context menu appIcon.setContextMenu(contextMenu); }); ``` -------------------------------- ### API History Block Example (Markdown) Source: https://github.com/itsidorkin28/sid-electron/blob/main/docs/development/api-history-migration-guide.md This markdown snippet shows an example of how to create an API History block for a deprecated function. It includes comments with YAML to specify the Pull Request URL and a breaking changes header, followed by the function's documentation. ```markdown #### `win.getTrafficLightPosition()` _macOS_ _Deprecated_ Returns `Point` - The custom position for the traffic light buttons in frameless window, `{ x: 0, y: 0 }` will be returned when there is no custom position. ``` -------------------------------- ### Create a basic HTML file for Electron renderer Source: https://github.com/itsidorkin28/sid-electron/blob/main/docs/tutorial/tutorial-2-first-app.md A minimal HTML file to be loaded into an Electron BrowserWindow. It includes basic meta tags for character set and content security policy. ```html
👋
``` -------------------------------- ### Request Get Upload Progress Source: https://github.com/itsidorkin28/sid-electron/blob/main/docs/api/client-request.md Returns an object containing the upload progress details, including whether the upload is active, started, and the current and total bytes uploaded. ```APIDOC ## GET /request/uploadProgress ### Description Returns an object with upload progress details. This method can be used with POST requests for file uploads or other data transfers. ### Method GET ### Endpoint /request/uploadProgress ### Parameters None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **active** (boolean) - Whether the request is currently active. If false, other properties are not set. - **started** (boolean) - Whether the upload has started. If false, `current` and `total` are 0. - **current** (Integer) - The number of bytes uploaded so far. - **total** (Integer) - The total number of bytes to be uploaded. #### Response Example ```json { "active": true, "started": true, "current": 1024, "total": 4096 } ``` ``` -------------------------------- ### Markdown ipcRenderer API Documentation Source: https://github.com/itsidorkin28/sid-electron/blob/main/docs/development/style-guide.md This markdown example illustrates the documentation for the `ipcRenderer` API. It features an embedded YAML block for change history and a note about its role in the renderer process. ```markdown # ipcRenderer Process: [Renderer](../glossary.md#renderer-process) ``` -------------------------------- ### Create Electron Window Instance Source: https://github.com/itsidorkin28/sid-electron/blob/main/docs/tutorial/tutorial-2-first-app.md This JavaScript function instantiates a new BrowserWindow with specified dimensions and loads an HTML file into it. It's a fundamental part of setting up the user interface for an Electron application. ```javascript const createWindow = () => { const win = new BrowserWindow({ width: 800, height: 600 }) win.loadFile('index.html') } ``` -------------------------------- ### Create HTTP Request with ClientRequest Source: https://github.com/itsidorkin28/sid-electron/blob/main/docs/api/client-request.md Instantiates a ClientRequest object to make an HTTP GET request to github.com. This example demonstrates how to specify protocol, hostname, port, and path for the request. ```javascript const request = net.request({ method: 'GET', protocol: 'https:', hostname: 'github.com', port: 443, path: '/' }) ``` -------------------------------- ### Call createWindow When App is Ready Source: https://github.com/itsidorkin28/sid-electron/blob/main/docs/tutorial/tutorial-2-first-app.md This code snippet demonstrates how to call the createWindow function after the Electron app has become ready. It uses the app.whenReady() API, which returns a promise that resolves when the app is ready to create windows. ```javascript app.whenReady().then(() => { createWindow() }) ``` -------------------------------- ### Example TraceConfig for Chrome DevTools Source: https://github.com/itsidorkin28/sid-electron/blob/main/docs/api/structures/trace-config.md This JavaScript object demonstrates a typical TraceConfig setup that closely resembles the tracing configuration used by Chrome DevTools. It specifies the recording mode and includes/excludes specific tracing categories. ```javascript { recording_mode: 'record-until-full', included_categories: [ 'devtools.timeline', 'disabled-by-default-devtools.timeline', 'disabled-by-default-devtools.timeline.frame', 'disabled-by-default-devtools.timeline.stack', 'v8.execute', 'blink.console', 'blink.user_timing', 'latencyInfo', 'disabled-by-default-v8.cpu_profiler', 'disabled-by-default-v8.cpu_profiler.hires' ], excluded_categories: ['*'] } ``` -------------------------------- ### Get Traffic Light Position (macOS - Deprecated) Source: https://github.com/itsidorkin28/sid-electron/blob/main/docs/development/api-history-migration-guide.md Retrieves the custom position of traffic light buttons in a frameless window on macOS. Returns { x: 0, y: 0 } if no custom position is set. This method is deprecated. ```javascript const position = win.getTrafficLightPosition(); console.log(position); // { x: number, y: number } ``` -------------------------------- ### Import Electron modules (app and BrowserWindow) Source: https://github.com/itsidorkin28/sid-electron/blob/main/docs/tutorial/tutorial-2-first-app.md Imports the 'app' and 'BrowserWindow' modules from the Electron library using CommonJS syntax. 'app' manages the application lifecycle, and 'BrowserWindow' creates application windows. ```js const { app, BrowserWindow } = require('electron') ``` -------------------------------- ### Flash Frame for Attention in Electron Source: https://github.com/itsidorkin28/sid-electron/blob/main/docs/tutorial/windows-taskbar.md Highlights the taskbar button to get the user's attention, similar to a bounce effect. The flashFrame method takes a boolean argument to start or stop the flashing. It's important to disable the flash, often when the window gains focus, to avoid persistent flashing. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() win.once('focus', () => win.flashFrame(false)) win.flashFrame(true) ``` -------------------------------- ### Select HID Devices in Electron Source: https://github.com/itsidorkin28/sid-electron/blob/main/docs/tutorial/devices.md This example illustrates how to select HID devices in Electron using the `select-hid-device` event on the Session. It also shows how to handle device addition/removal events and set default permissions. ```javascript session.defaultSession.on('select-hid-device', (event, callback, details) => { // Automatically select the first available HID device callback(details.deviceList[0].deviceId); }); session.defaultSession.setDevicePermissionHandler((device) => { // Grant default permission to the HID device return true; }); ``` -------------------------------- ### Create Application and Context Menus with Electron Source: https://context7.com/itsidorkin28/sid-electron/llms.txt Demonstrates how to build application-wide menus and context menus using Electron's Menu class. It includes defining menu items with labels, accelerators, click handlers, and roles. Dependencies include the 'electron' module. ```javascript const { Menu, app, shell, BrowserWindow } = require('electron') // Create application menu const template = [ { label: 'File', submenu: [ { label: 'New File', accelerator: 'CmdOrCtrl+N', click: () => createNewFile() }, { label: 'Open...', accelerator: 'CmdOrCtrl+O', click: async () => { const files = await openFileDialog() if (files) loadFiles(files) } }, { type: 'separator' }, { label: 'Save', accelerator: 'CmdOrCtrl+S', click: () => saveCurrentFile() }, { type: 'separator' }, { role: 'quit' } ] }, { label: 'Edit', submenu: [ { role: 'undo' }, { role: 'redo' }, { type: 'separator' }, { role: 'cut' }, { role: 'copy' }, { role: 'paste' }, { role: 'selectAll' } ] }, { label: 'View', submenu: [ { role: 'reload' }, { role: 'forceReload' }, { role: 'toggleDevTools' }, { type: 'separator' }, { role: 'resetZoom' }, { role: 'zoomIn' }, { role: 'zoomOut' }, { type: 'separator' }, { role: 'togglefullscreen' } ] }, { label: 'Help', submenu: [ { label: 'Documentation', click: () => shell.openExternal('https://electronjs.org/docs') } ] } ] const menu = Menu.buildFromTemplate(template) Menu.setApplicationMenu(menu) // Context menu function showContextMenu(win) { const contextMenu = Menu.buildFromTemplate([ { label: 'Cut', role: 'cut' }, { label: 'Copy', role: 'copy' }, { label: 'Paste', role: 'paste' }, { type: 'separator' }, { label: 'Select All', role: 'selectAll' } ]) contextMenu.popup({ window: win }) } ``` -------------------------------- ### Electron IPC with IndexedDB Operations (JavaScript) Source: https://github.com/itsidorkin28/sid-electron/blob/main/spec/fixtures/api/localstorage-and-indexeddb.html This snippet illustrates performing IndexedDB operations (delete, open, create object store, add, get) from an Electron renderer process using `ipcRenderer`. It handles database creation, data insertion, and data retrieval, sending status updates back via IPC. ```javascript const {ipcRenderer} = require('electron'); const deleteRequest = window.indexedDB.deleteDatabase('testdb'); deleteRequest.onerror = deleteRequest.onsuccess = (event) => { const openRequest = window.indexedDB.open('testdb'); openRequest.onupgradeneeded = (event) => { const db = event.target.result; db.onerror = (event) => { console.error(event); }; const objectStore = db.createObjectStore('testdata'); objectStore.createIndex('test', ''); }; openRequest.onsuccess = (event) => { const db = event.target.result; const addRequest = db.transaction("testdata", "readwrite").objectStore("testdata").add("hello indexeddb", 'test'); addRequest.onsuccess = () => { ipcRenderer.send('indexeddb-ready'); }; }; }; ipcRenderer.on('get-indexeddb', () => { const openRequest = window.indexedDB.open('testdb'); openRequest.onerror = (event) => { console.error(event); }; openRequest.onsuccess = (event) => { const db = event.target.result; if (!db.objectStoreNames.contains('testdata')) { ipcRenderer.send('result-indexeddb', undefined); return; } const getRequest = db.transaction('testdata', 'readonly').objectStore('testdata').get('test'); getRequest.onsuccess = (event) => { ipcRenderer.send('result-indexeddb', event.target.result); }; }; }); ``` -------------------------------- ### Send Synchronous Message with ipcRenderer in Electron Source: https://github.com/itsidorkin28/sid-electron/blob/main/spec/fixtures/api/send-sync-message.html This snippet shows how to send a synchronous message from the renderer process to the main process using Electron's ipcRenderer.sendSync method. It requires the 'electron' module to be installed. The function takes a channel name and a message payload as arguments and blocks until a response is received from the main process. ```javascript var ipcRenderer = require('electron').ipcRenderer; ipcRenderer.sendSync('send-sync-message', 'message'); ``` -------------------------------- ### Create New BrowserWindow (JavaScript) Source: https://github.com/itsidorkin28/sid-electron/blob/main/docs/fiddles/windows/manage-windows/new-window/index.html Demonstrates the creation of a new BrowserWindow instance in Electron. This basic example shows how to instantiate a window with specified dimensions. Further customization is possible via numerous options detailed in the Electron documentation. ```javascript var win = new BrowserWindow({ width: 400, height: 225 }) ``` -------------------------------- ### Preventing popups with `