### Start Electron REPL with global installation Source: https://github.com/discord/electron/blob/main/docs/tutorial/repl.md Run the Electron REPL when electron or electron-prebuilt is installed globally. This command starts an interactive REPL for the main process. ```sh electron --interactive ``` -------------------------------- ### Start and stop tracing with contentTracing Source: https://github.com/discord/electron/blob/main/docs/api/content-tracing.md Use this example to record tracing data for 5 seconds. It starts recording with all categories, waits, then stops and logs the path to the trace file. Requires the app'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) })() }) ``` -------------------------------- ### Install the snap with sudo snap install Source: https://github.com/discord/electron/blob/main/docs/tutorial/snapcraft.md Installs the locally built snap. The --dangerous flag is required because the snap is not signed. ```sh sudo snap install electron-packager-hello-world_0.1_amd64.snap --dangerous ``` -------------------------------- ### --js-flags example Source: https://github.com/discord/electron/blob/main/docs/api/command-line-switches.md Example of passing Node.js flags via the --js-flags command line switch when starting Electron. ```sh $ electron --js-flags="--harmony_proxies --harmony_collections" your-app ``` -------------------------------- ### Example folder structure Source: https://github.com/discord/electron/blob/main/docs/breaking-changes.md Example folder structure used to illustrate the webkitdirectory behavior change. ```console folder ├── file1 ├── file2 └── file3 ``` -------------------------------- ### Install Electron with npm Source: https://github.com/discord/electron/blob/main/docs/tutorial/quick-start.md Commands to create a project folder, initialize a package.json, and install Electron as a dev dependency. ```sh mkdir my-electron-app && cd my-electron-app npm init -y npm i --save-dev electron ``` -------------------------------- ### Start and stop netLog logging Source: https://github.com/discord/electron/blob/main/docs/api/net-log.md Shows how to start and stop network logging using the netLog module. The example uses app.whenReady() to ensure the app is ready before calling startLogging, then stops logging and logs the path where the net-log file was written. ```javascript const { 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) }) ``` -------------------------------- ### package.json with start script Source: https://github.com/discord/electron/blob/main/docs/tutorial/quick-start.md Adds a start script that runs Electron with the current directory, enabling npm start. ```json { "name": "my-electron-app", "version": "0.1.0", "main": "main.js", "scripts": { "start": "electron ." } } ``` -------------------------------- ### Start Electron REPL with local dependency Source: https://github.com/discord/electron/blob/main/docs/tutorial/repl.md Run the Electron REPL when electron or electron-prebuilt is installed as a local project dependency. This command starts an interactive REPL for the main process. ```sh ./node_modules/.bin/electron --interactive ``` -------------------------------- ### --auth-server-whitelist example Source: https://github.com/discord/electron/blob/main/docs/api/command-line-switches.md Example of the --auth-server-whitelist flag with a comma-separated list of servers. Without the * prefix, the URL must match exactly. ```sh --auth-server-whitelist='*example.com, *foobar.com, *baz' ``` -------------------------------- ### BrowserWindowProxy example Source: https://github.com/discord/electron/blob/main/docs/api/window-open.md Example usage of window.open() with BrowserWindowProxy, including main process handler and renderer code. ```APIDOC ## BrowserWindowProxy example ### Description Example of using window.open() in a renderer with a BrowserWindowProxy and setting a window open handler in the main process. ### Main Process Example ```javascript // main.js const mainWindow = new BrowserWindow() mainWindow.webContents.setWindowOpenHandler(({ url }) => { if (url.startsWith('https://github.com/')) { return true } return false }) mainWindow.webContents.on('did-create-window', (childWindow) => { // For example... childWindow.webContents('will-navigate', (e) => { e.preventDefault() }) }) ``` ### Renderer Process Example ```javascript // renderer.js const windowProxy = window.open('https://github.com/', null, 'minimizable=false') windowProxy.postMessage('hi', '*') ``` ``` -------------------------------- ### Native Window example Source: https://github.com/discord/electron/blob/main/docs/api/window-open.md Example usage of window.open() with nativeWindowOpen enabled, showing how to access the child window directly. ```APIDOC ## Native Window example ### Description Example of using window.open() with nativeWindowOpen enabled, returning a native Window instance that can be accessed directly. ### Main Process Example ```javascript // main.js const mainWindow = new BrowserWindow({ webPreferences: { nativeWindowOpen: true } }) // In this example, only windows with the `about:blank` url will be created. // All other urls will be blocked. mainWindow.webContents.setWindowOpenHandler(({ url }) => { if (url === 'about:blank') { return { frame: false, fullscreenable: false, backgroundColor: 'black', webPreferences: { preload: 'my-child-window-preload-script.js' } } } return false }) ``` ### Renderer Process Example ```javascript // renderer process (mainWindow) const childWindow = window.open('', 'modal') childWindow.document.write('

Hello

') ``` ``` -------------------------------- ### Install clang-format and git-clang-format via npm Source: https://github.com/discord/electron/blob/main/docs/development/clang-format.md Installs the clang-format and git-clang-format tools globally using npm. Run this before using the formatting commands. ```bash npm install -g clang-format ``` -------------------------------- ### Install WebDriverJS Source: https://github.com/discord/electron/blob/main/docs/tutorial/using-selenium-and-webdriver.md Install the selenium-webdriver package using npm. ```sh $ npm install selenium-webdriver ``` -------------------------------- ### Run the Electron app Source: https://github.com/discord/electron/blob/main/docs/tutorial/quick-start.md Command to start the Electron application using the configured start script. ```sh npm start ``` -------------------------------- ### Install electron-windows-store CLI Source: https://github.com/discord/electron/blob/main/docs/tutorial/windows-store-guide.md Install the electron-windows-store command-line tool globally via npm. This is the prerequisite step before packaging an Electron app as an .appx package. ```bash npm install -g electron-windows-store ``` -------------------------------- ### --proxy-bypass-list example Source: https://github.com/discord/electron/blob/main/docs/api/command-line-switches.md Example of using app.commandLine.appendSwitch with the proxy-bypass-list flag. The flag only has effect when used with --proxy-server. ```javascript const { app } = require('electron') app.commandLine.appendSwitch('proxy-bypass-list', ';*.google.com;*foo.com;1.2.3.4:5678') ``` -------------------------------- ### Install asar and package an app Source: https://github.com/discord/electron/blob/main/docs/tutorial/application-packaging.md Install the asar utility globally with npm, then package your app directory into an asar archive using the asar pack command. ```sh $ npm install -g asar ``` ```sh $ asar pack your-app app.asar ``` -------------------------------- ### Install Surf via npm Source: https://github.com/discord/electron/blob/main/docs/tutorial/application-distribution.md Installs the Surf build tool globally via npm. Required before creating a custom release with surf-build. ```bash npm install -g surf-build@latest ``` -------------------------------- ### Install Ubuntu build dependencies with apt-get Source: https://github.com/discord/electron/blob/main/docs/development/build-instructions-linux.md Install the required development libraries and tools on Ubuntu. This includes clang, GTK 3 and libnotify development headers, and other dependencies needed to build Electron. ```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 ``` -------------------------------- ### Install Electron and run quick-start app Source: https://github.com/discord/electron/blob/main/README.md Commands for installing Electron as a dependency and for cloning and running the quick-start repository. Use the --save-exact flag for Electron before version 2 due to non-semver versioning; after 2.0.0, it is not needed. ```sh npm install electron --save-dev [--save-exact] ``` ```sh git clone https://github.com/electron/electron-quick-start cd electron-quick-start npm install npm start ``` -------------------------------- ### Install and start ChromeDriver for WebDriverJs Source: https://github.com/discord/electron/blob/main/docs/tutorial/using-selenium-and-webdriver.md Install electron-chromedriver and run the chromedriver binary. The output shows it starts on port 9515 and only allows local connections. ```sh $ npm install electron-chromedriver $ ./node_modules/.bin/chromedriver Starting ChromeDriver (v2.10.291558) on port 9515 Only local connections are allowed. ``` -------------------------------- ### Install and start ChromeDriver for WebdriverIO Source: https://github.com/discord/electron/blob/main/docs/tutorial/using-selenium-and-webdriver.md Install electron-chromedriver and run chromedriver with the --url-base=wd/hub and --port=9515 flags. The output shows it starts on port 9515 and only allows local connections. ```sh $ npm install electron-chromedriver $ ./node_modules/.bin/chromedriver --url-base=wd/hub --port=9515 Starting ChromeDriver (v2.10.291558) on port 9515 Only local connections are allowed. ``` -------------------------------- ### Set up build environment and generate Testing config (Unix) Source: https://github.com/discord/electron/blob/main/docs/development/build-instructions-gn.md Initializes the build environment by changing to the src directory, setting CHROMIUM_BUILDTOOLS_PATH, optionally configuring sccache via GN_EXTRA_ARGS, and generating the Testing build configuration with gn gen. ```sh $ cd src $ export CHROMIUM_BUILDTOOLS_PATH=`pwd`/buildtools # this next line is needed only if building with sccache $ export GN_EXTRA_ARGS="${GN_EXTRA_ARGS} cc_wrapper="${PWD}/electron/external_binaries/sccache"" $ gn gen out/Testing --args="import(\"//electron/build/args/testing.gn\") $GN_EXTRA_ARGS" ``` -------------------------------- ### Create and use a BrowserView in the main process Source: https://github.com/discord/electron/blob/main/docs/api/browser-view.md Shows how to create a BrowserView, attach it to a BrowserWindow, set its bounds, and load a URL. Requires the 'electron' module and must run in the main process. ```javascript // In the main process. const { BrowserView, BrowserWindow } = require('electron') 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') ``` -------------------------------- ### new BrowserWindow([options]) Source: https://github.com/discord/electron/blob/main/docs/api/browser-window.md Documentation for the BrowserWindow constructor, including all available options and their defaults. ```APIDOC ## new BrowserWindow([options]) ### Description Creates a new BrowserWindow instance with the specified options. This is the constructor for the BrowserWindow class in Electron, used to create and control browser windows. ### Method Constructor ### Endpoint `new BrowserWindow([options])` ### Parameters #### Options - **width** (Integer) - Optional - Window's width in pixels. Default is `800`. - **height** (Integer) - Optional - Window's height in pixels. Default is `600`. - **x** (Integer) - Optional - Window's left offset from screen. Default is to center the window. - **y** (Integer) - Optional - Window's top offset from screen. Default is to center the window. - **useContentSize** (Boolean) - Optional - The `width` and `height` would be used as web page's size, which means the actual window's size will include window frame's size and be slightly larger. Default is `false`. - **center** (Boolean) - Optional - Show window in the center of the screen. Default is `false`. - **minWidth** (Integer) - Optional - Window's minimum width. Default is `0`. - **minHeight** (Integer) - Optional - Window's minimum height. Default is `0`. - **maxWidth** (Integer) - Optional - Window's maximum width. Default is no limit. - **maxHeight** (Integer) - Optional - Window's maximum height. Default is no limit. - **resizable** (Boolean) - Optional - Whether window is resizable. Default is `true`. - **movable** (Boolean) - Optional - Whether window is movable. This is not implemented on Linux. Default is `true`. - **minimizable** (Boolean) - Optional - Whether window is minimizable. This is not implemented on Linux. Default is `true`. - **maximizable** (Boolean) - Optional - Whether window is maximizable. This is not implemented on Linux. Default is `true`. - **closable** (Boolean) - Optional - Whether window is closable. This is not implemented on Linux. Default is `true`. - **focusable** (Boolean) - Optional - Whether the window can be focused. On Windows setting `focusable: false` also implies setting `skipTaskbar: true`. On Linux setting `focusable: false` makes the window stop interacting with wm, so the window will always stay on top in all workspaces. Default is `true`. - **alwaysOnTop** (Boolean) - Optional - Whether the window should always stay on top of other windows. Default is `false`. - **fullscreen** (Boolean) - Optional - Whether the window should show in fullscreen. When explicitly set to `false` the fullscreen button will be hidden or disabled on macOS. Default is `false`. - **fullscreenable** (Boolean) - Optional - Whether the window can be put into fullscreen mode. On macOS, also whether the maximize/zoom button should toggle full screen mode or maximize window. Default is `true`. - **simpleFullscreen** (Boolean) - Optional - Use pre-Lion fullscreen on macOS. Default is `false`. - **skipTaskbar** (Boolean) - Optional - Whether to show the window in taskbar. Default is `false`. - **kiosk** (Boolean) - Optional - The kiosk mode. Default is `false`. - **title** (String) - Optional - Default window title. Default is `"Electron"`. If the HTML tag `` is defined in the HTML file loaded by `loadURL()`, this property will be ignored. - **icon** (NativeImage | String) - Optional - The window icon. On Windows it is recommended to use ICO icons to get best visual effects, you can also leave it undefined so the executable's icon will be used. - **show** (Boolean) - Optional - Whether window should be shown when created. Default is `true`. - **paintWhenInitiallyHidden** (Boolean) - Optional - Whether the renderer should be active when `show` is `false` and it has been created. In order for `paintWhenInitiallyHidden` to have an effect, `show` must be set to `false`. Note that this only affects the initial creation of the window. Default is `true`. - **frame** (Boolean) - Optional - Specify `false` to create a Frameless Window. Default is `true`. - **parent** (BrowserWindow) - Optional - Specify parent window. Default is `null`. - **modal** (Boolean) - Optional - Whether this is a modal window. This only works when the window is a child window. Default is `false`. - **acceptFirstMouse** (Boolean) - Optional - Whether the web view accepts a single mouse-down event that simultaneously activates the window. Default is `false`. - **disableAutoHideCursor** (Boolean) - Optional - Whether to hide cursor when typing. Default is `false`. - **autoHideMenuBar** (Boolean) - Optional - Auto hide the menu bar unless the `Alt` key is pressed. Default is `false`. - **enableLargerThanScreen** (Boolean) - Optional - Enable the window to be resized larger than screen. Only relevant for macOS, as other OSes allow larger-than-screen windows by default. Default is `false`. - **backgroundColor** (String) - Optional - Window's background color as a hexadecimal value, like `#66CD00` or `#FFF` or `#80FFFFFF` (alpha in #AARRGGBB format is supported if `transparent` is set to `true`). Default is `#FFF` (white). - **hasShadow** (Boolean) - Optional - Whether window should have a shadow. Default is `true`. - **opacity** (Number) - Optional - Set the initial opacity of the window, between 0.0 (fully transparent) and 1.0 (fully opaque). This is only implemented on Windows and macOS. - **darkTheme** (Boolean) - Optional - Forces using dark theme for the window, only works on some GTK+3 desktop environments. Default is `false`. - **transparent** (Boolean) - Optional - Makes the window transparent. Default is `false`. On Windows, does not work unless the window is frameless. - **type** (String) - Optional - The type of window, default is normal window. See more about this below. - **visualEffectState** (String) - Optional - Specify how the material appearance should reflect window activity state on macOS. Must be used with the `vibrancy` property. Possible values are: `followWindow`, `active`, `inactive`. - **titleBarStyle** (String) - Optional - The style of window title bar. Default is `default`. Possible values are: `default`, `hidden`, `hiddenInset`. - **customButtonsOnHover** (Boolean) - Optional - Draw custom close, and minimize buttons on macOS frameless windows. These buttons will not display unless hovered over in the top left of the window. These custom buttons prevent issues with mouse events that occur with the standard window toolbar buttons. **Note:** This option is currently experimental. - **trafficLightPosition** (Point) - Optional - Set a custom position for the traffic light buttons. Can only be used with `titleBarStyle` set to `hidden`. - **fullscreenWindowTitle** (Boolean) - Optional - Shows the title in the title bar in full screen mode on macOS for all `titleBarStyle` options. Default is `false`. - **thickFrame** (Boolean) - Optional - Use `WS_THICKFRAME` style for frameless windows on Windows, which adds standard window frame. Setting it to `false` will remove window shadow and window animations. Default is `true`. - **vibrancy** (String) - Optional - Add a type of vibrancy effect to the window, only on macOS. Can be `appearance-based`, `light`, `dark`, `titlebar`, `selection`, `menu`, `popover`, `sidebar`, `medium-light`, `ultra-dark`, `header`, `sheet`, `window`, `hud`, `fullscreen-ui`, `tooltip`, `content`, `under-window`, or `under-page`. Please note that using `frame: false` in combination with a vibrancy value requires that you use a non-default `titleBarStyle` as well. Also note that `appearance-based`, `light`, `dark`, `medium-light`, and `ultra-dark` have been deprecated and will be removed in an upcoming version of macOS. - **zoomToPageWidth** (Boolean) - Optional - Controls the behavior on macOS when option-clicking the green stoplight button on the toolbar or by clicking the Window > Zoom menu item. If `true`, the window will grow to the preferred width of the web page when zoomed, `false` will cause it to zoom to the width of the screen. This will also affect the behavior when calling `maximize()` directly. Default is `false`. - **tabbingIdentifier** (String) - Optional - Tab group name, allows opening the window as a native tab on macOS 10.12+. Windows with the same tabbing identifier will be grouped together. This also adds a native new tab button to your window's tab bar and allows your `app` and window to receive the `new-window-for-tab` event. - **webPreferences** (Object) - Optional - Settings of web page's features. - **devTools** (Boolean) - Optional - Whether to enable DevTools. If it is set to `false`, can not use `BrowserWindow.webContents.openDevTools()` to open DevTools. Default is `true`. ### Returns A new BrowserWindow instance. ``` -------------------------------- ### Clone Electron repository with gclient Source: https://github.com/discord/electron/blob/main/docs/development/build-instructions-gn.md Initial setup to fetch the Electron source and its dependencies. Run these commands in a new directory. The gclient sync command will take a while and downloads all required dependencies. ```sh $ mkdir electron && cd electron $ gclient config --name "src/electron" --unmanaged https://github.com/electron/electron $ gclient sync --with_branch_heads --with_tags # This will take a while, go get a coffee. ``` -------------------------------- ### Get real file path from dragged files Source: https://github.com/discord/electron/blob/main/docs/api/file-object.md Use this HTML/JavaScript example to handle drag-and-drop of files onto a web page and log their real filesystem paths via the Electron-specific `path` attribute on the File object. The example adds drop and dragover event listeners to prevent default browser behavior and iterate over dropped files. ```html <div id="holder"> Drag your file here </div> <script> document.addEventListener('drop', (e) => { e.preventDefault(); e.stopPropagation(); for (const f of e.dataTransfer.files) { console.log('File(s) you dragged here: ', f.path) } }); document.addEventListener('dragover', (e) => { e.preventDefault(); e.stopPropagation(); }); </script> ``` -------------------------------- ### Example .desktop file with launcher actions Source: https://github.com/discord/electron/blob/main/docs/tutorial/linux-desktop-actions.md Defines custom launcher actions (PlayPause, Next, Previous) for a Unity launcher. Each action has Name, Exec, and OnlyShowIn properties. The Exec command is executed when the user clicks the shortcut menu item. ```plaintext Actions=PlayPause;Next;Previous [Desktop Action PlayPause] Name=Play-Pause Exec=audacious -t OnlyShowIn=Unity; [Desktop Action Next] Name=Next Exec=audacious -f OnlyShowIn=Unity; [Desktop Action Previous] Name=Previous Exec=audacious -r OnlyShowIn=Unity; ``` -------------------------------- ### Get resource usage with webFrame.getResourceUsage() Source: https://github.com/discord/electron/blob/main/docs/api/web-frame.md Retrieves Blink's internal memory cache usage details. The example logs the returned object, which includes counts and sizes for images, stylesheets, fonts, and other resources. ```javascript const { webFrame } = require('electron') console.log(webFrame.getResourceUsage()) ``` ```javascript { images: { count: 22, size: 2549, liveSize: 2542 }, cssStyleSheets: { /* same with "images" */ }, xslStyleSheets: { /* same with "images" */ }, fonts: { /* same with "images" */ }, other: { /* same with "images" */ } } ``` -------------------------------- ### HTML form with unsupported '--' key Source: https://github.com/discord/electron/blob/main/docs/api/structures/post-body.md Example of an HTML form that submits to a new window with POST. The key '--theKey' starts with '--', which is not supported and will cause the form to be submitted as multipart/form-data when nativeWindowOpen is false in webPreferences. ```html <form target="_blank" method="POST" enctype="application/x-www-form-urlencoded" action="https://postman-echo.com/post" > <input type="text" name="--theKey"> <input type="submit"> </form> ``` -------------------------------- ### Run electron-installer-snap with --src Source: https://github.com/discord/electron/blob/main/docs/tutorial/snapcraft.md Runs electron-installer-snap from the command line, specifying the source directory of the packaged Electron application with the --src parameter. Requires snapcraft to be in the PATH. ```sh npx electron-installer-snap --src=out/myappname-linux-x64 ``` -------------------------------- ### Native Window example - main process Source: https://github.com/discord/electron/blob/main/docs/api/window-open.md Enables nativeWindowOpen and sets a handler that only allows about:blank windows, customizing their BrowserWindow options. This demonstrates how to control native window creation. ```javascript // main.js const mainWindow = new BrowserWindow({ webPreferences: { nativeWindowOpen: true } }) // In this example, only windows with the `about:blank` url will be created. // All other urls will be blocked. mainWindow.webContents.setWindowOpenHandler(({ url }) => { if (url === 'about:blank') { return { frame: false, fullscreenable: false, backgroundColor: 'black', webPreferences: { preload: 'my-child-window-preload-script.js' } } } return false }) ``` -------------------------------- ### Query and handle service workers with session.defaultSession.serviceWorkers Source: https://github.com/discord/electron/blob/main/docs/api/service-workers.md Shows how to access the ServiceWorkers instance from the default session, get all running service workers, and listen for console messages. The example logs the message details and the service worker info from the version ID. ```javascript const { session } = require('electron') // Get all service workers. console.log(session.defaultSession.serviceWorkers.getAllRunning()) // Handle logs and get service worker info session.defaultSession.serviceWorkers.on('console-message', (event, messageDetails) => { console.log( 'Got service worker message', messageDetails, 'from', session.defaultSession.serviceWorkers.getFromVersionID(messageDetails.versionId) ) }) ``` -------------------------------- ### Update main.js to create an online status window Source: https://github.com/discord/electron/blob/main/docs/tutorial/online-offline-events.md Adds online/offline detection to the main process by creating a hidden BrowserWindow that loads a URL. Use this after setting up the app from the Quick Start Guide. The window is created with zero dimensions and hidden, then loads the given URL. ```javascript const { app, BrowserWindow } = require('electron') let onlineStatusWindow app.whenReady().then(() => { onlineStatusWindow = new BrowserWindow({ width: 0, height: 0, show: false }) onlineStatusWindow.loadURL(`file://${__dirname}/index.html`) }) ``` -------------------------------- ### Set taskbar progress with BrowserWindow.setProgressBar Source: https://github.com/discord/electron/blob/main/docs/tutorial/progress-bar.md Add these lines to the main.js file of an Electron app created from the Quick Start Guide. The setProgressBar method accepts a number between 0 and 1; negative values remove the bar and values greater than 1 switch to indeterminate mode (Windows-only). ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() win.setProgressBar(0.5) ``` -------------------------------- ### new BrowserWindow([options]) Source: https://github.com/discord/electron/blob/main/docs/api/browser-window.md Documentation for the BrowserWindow constructor, including all available options and platform-specific notices. ```APIDOC ## new BrowserWindow([options]) ### Description Creates a new BrowserWindow with native properties as set by the options. The BrowserWindow class is an EventEmitter and is used to create and control browser windows in the main process. ### Method Constructor ### Endpoint `new BrowserWindow([options])` ### Parameters #### Options - **width** (Integer) - Optional - Window's width in pixels. Default is `800`. - **height** (Integer) - Optional - Window's height in pixels. Default is `600`. - **x** (Integer) - Optional - (required if y is used) Window's left offset from screen. Default is to center the window. - **y** (Integer) - Optional - (required if x is used) Window's top offset from screen. Default is to center the window. - **useContentSize** (Boolean) - Optional - The `width` and `height` would be used as web page's size, which means the actual window's size will include window frame's size and be slightly larger. Default is `false`. - **center** (Boolean) - Optional - Show window in the center of the screen. - **minWidth** (Integer) - Optional - Window's minimum width. Default is `0`. - **minHeight** (Integer) - Optional - Window's minimum height. Default is `0`. - **maxWidth** (Integer) - Optional - Window's maximum width. Default is no limit. - **maxHeight** (Integer) - Optional - Window's maximum height. Default is no limit. - **resizable** (Boolean) - Optional - Whether window is resizable. Default is `true`. - **movable** (Boolean) - Optional - Whether window is movable. This is not implemented on Linux. Default is `true`. - **minimizable** (Boolean) - Optional - Whether window is minimizable. This is not implemented on Linux. Default is `true`. - **maximizable** (Boolean) - Optional - Whether window is maximizable. This is not implemented on Linux. Default is `true`. - **closable** (Boolean) - Optional - Whether window is closable. This is not implemented on Linux. Default is `true`. - **focusable** (Boolean) - Optional - Whether the window can be focused. Default is `true`. On Windows setting `focusable: false` also implies setting `skipTaskbar: true`. On Linux setting `focusable: false` makes the window stop interacting with wm, so the window will always stay on top in all workspaces. - **alwaysOnTop** (Boolean) - Optional - Whether the window should always stay on top of other windows. Default is `false`. - **fullscreen** (Boolean) - Optional - Whether the window should show in fullscreen. When explicitly set to `false` the fullscreen button will be hidden or disabled on macOS. Default is `false`. - **fullscreenable** (Boolean) - Optional - Whether the window can be put into fullscreen mode. On macOS, also whether the maximize/zoom button should toggle full screen mode or maximize window. Default is `true`. - **simpleFullscreen** (Boolean) - Optional - Use pre-Lion fullscreen on macOS. Default is `false`. - **skipTaskbar** (Boolean) - Optional - Whether to show the window in taskbar. Default is `false`. - **kiosk** (Boolean) - Optional - Whether the window is in kiosk mode. Default is `false`. - **title** (String) - Optional - Default window title. Default is `"Electron"`. If the HTML tag `<title>` is defined in the HTML file loaded by `loadURL()`, this property will be ignored. - **icon** (NativeImage | String) - Optional - The window icon. On Windows it is recommended to use `ICO` icons to get best visual effects, you can also leave it undefined so the executable's icon will be used. - **show** (Boolean) - Optional - Whether window should be shown when created. Default is `true`. - **paintWhenInitiallyHidden** (Boolean) - Optional - Whether the renderer should be active when `show` is `false` and it has just been created. In order for `document.visibilityState` to work correctly on first load with `show: false` you should set this to `false`. Setting this to `false` will cause the `ready-to-show` event to not fire. Default is `true`. - **frame** (Boolean) - Optional - Specify `false` to create a Frameless Window. Default is `true`. - **parent** (BrowserWindow) - Optional - Specify parent window. Default is `null`. - **modal** (Boolean) - Optional - Whether this is a modal window. This only works when the window is a child window. Default is `false`. - **acceptFirstMouse** (Boolean) - Optional - Whether the web view accepts a single mouse-down event that simultaneously activates the window. Default is `false`. - **disableAutoHideCursor** (Boolean) - Optional - Whether to hide cursor when typing. ### Request Example ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 600, title: 'Example Window' }) ``` ### Response Returns a new BrowserWindow instance. ### Platform Notices - On macOS modal windows will be displayed as sheets attached to the parent window. - On macOS the child windows will keep the relative position to parent window when parent window moves, while on Windows and Linux child windows will not move. - On Linux the type of modal windows will be changed to `dialog`. - On Linux many desktop environments do not support hiding a modal window. ``` -------------------------------- ### Install aws-sdk with npm install --save Source: https://github.com/discord/electron/blob/main/docs/tutorial/quick-start.md Installs the aws-sdk module as a dependency for your Electron app. ```sh npm install --save aws-sdk ``` -------------------------------- ### Clone and open electron-quick-start in VSCode Source: https://github.com/discord/electron/blob/main/docs/tutorial/debugging-vscode.md Clones the electron-quick-start repository and opens it in VSCode. This is the first step for debugging an Electron app's main process. ```sh $ git clone git@github.com:electron/electron-quick-start.git $ code electron-quick-start ``` -------------------------------- ### Set up Windows Desktop App Converter Source: https://github.com/discord/electron/blob/main/docs/tutorial/windows-store-guide.md Before using the electron-windows-store CLI with container virtualization, set the execution policy to bypass and run the Desktop App Converter setup with the base image. The setup may prompt for a reboot; if so, restart and run the command again. ```powershell Set-ExecutionPolicy bypass ``` ```powershell .\DesktopAppConverter.ps1 -Setup -BaseImage .\BaseImage-14316.wim ``` -------------------------------- ### Install WebdriverIO Source: https://github.com/discord/electron/blob/main/docs/tutorial/using-selenium-and-webdriver.md Install the webdriverio package using npm. ```sh $ npm install webdriverio ``` -------------------------------- ### Install Electron with custom platform Source: https://github.com/discord/electron/blob/main/docs/tutorial/installation.md Use the --platform flag to specify the platform (e.g., win32, linux, etc.). ```shell npm install --platform=win32 electron ``` -------------------------------- ### Install update-electron-app Source: https://github.com/discord/electron/blob/main/docs/tutorial/updates.md Installs the update-electron-app module, which is preconfigured for use with update.electronjs.org. ```sh npm install update-electron-app ``` -------------------------------- ### Install Spectron Source: https://github.com/discord/electron/blob/main/docs/tutorial/using-selenium-and-webdriver.md Install Spectron as a dev dependency using npm. ```sh $ npm install --save-dev spectron ``` -------------------------------- ### Create a BrowserWindow instance Source: https://github.com/discord/electron/blob/main/docs/api/browser-window.md Creates a BrowserWindow instance and loads a URL. This is the basic setup for using instance properties and methods. ```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') ``` -------------------------------- ### Install Electron globally Source: https://github.com/discord/electron/blob/main/docs/tutorial/installation.md Installs the electron command globally in your $PATH. ```sh npm install electron -g ``` -------------------------------- ### Install and rebuild native modules with electron-rebuild Source: https://github.com/discord/electron/blob/main/docs/tutorial/using-native-node-modules.md Install the electron-rebuild package and run it after every npm install to rebuild native modules for Electron. On Windows, use the .cmd variant if the command fails. ```sh npm install --save-dev electron-rebuild # Every time you run "npm install", run this: ./node_modules/.bin/electron-rebuild # On Windows if you have trouble, try: .\node_modules\.bin\electron-rebuild.cmd ``` -------------------------------- ### BrowserWindow Constructor Options Source: https://github.com/discord/electron/blob/main/docs/api/browser-window.md Options for creating a BrowserWindow instance, including enableWebSQL, v8CacheOptions, and enablePreferredSizeMode. ```APIDOC ## BrowserWindow Constructor Options ### Description Options for creating a BrowserWindow instance. ### Parameters - **enableWebSQL** (Boolean) - Optional - Whether to enable the WebSQL API. Default is `true`. - **v8CacheOptions** (String) - Optional - Enforces the v8 code caching policy used by blink. Accepted values: `none`, `code`, `bypassHeatCheck`, `bypassHeatCheckAndEagerCompile`. Default is `code`. - **enablePreferredSizeMode** (Boolean) - Optional - Whether to enable preferred size mode. Default is `false`. ### Notes - Setting minimum or maximum window size with `minWidth`/`maxWidth`/`minHeight`/`maxHeight` only constrains the users. It won't prevent passing a size that does not follow size constraints to `setBounds`/`setSize` or to the constructor. - The possible values and behaviors of the `type` option are platform dependent: - On Linux: `desktop`, `dock`, `toolbar`, `splash`, `notification`. - On macOS: `desktop`, `textured`. - On Windows: `toolbar`. ``` -------------------------------- ### new Tray(image, [guid]) Source: https://github.com/discord/electron/blob/main/docs/api/tray.md Creates a new tray icon associated with the provided image. The optional guid parameter is Windows-specific and assigns a GUID to the tray icon for persistence of OS-level settings. ```APIDOC ## new Tray(image, [guid]) ### Description Creates a new tray icon associated with the provided image. The optional guid parameter is Windows-specific and assigns a GUID to the tray icon for persistence of OS-level settings. ### Method Constructor ### Parameters - `image` (NativeImage | String) - Required - The image to use for the tray icon. - `guid` (String) - Optional - Windows only. Assigns a GUID to the tray icon. If the executable is signed and the signature contains an organization in the subject line, the GUID is permanently associated with that signature. OS-level settings like the position of the tray icon in the system tray will persist even if the path to the executable changes. If the executable is not code-signed, the GUID is permanently associated with the path to the executable. Changing the path to the executable will break the creation of the tray icon and a new GUID must be used. It is highly recommended to use the GUID parameter only in conjunction with a code-signed executable. If an app defines multiple tray icons, each icon must use a separate GUID. ### Example ```javascript const { app, Tray } = require('electron') let tray = null app.whenReady().then(() => { tray = new Tray('/path/to/my/icon') }) ``` ``` -------------------------------- ### Install latest stable Electron Source: https://github.com/discord/electron/blob/main/docs/tutorial/electron-versioning.md Installs the most recent stable build of Electron as a dev dependency. ```sh npm install --save-dev electron ``` -------------------------------- ### Create snapcraft.yaml for existing Debian package (classic confinement) Source: https://github.com/discord/electron/blob/main/docs/tutorial/snapcraft.md Configure Snapcraft to package an existing Debian package as a snap. Uses classic confinement and specifies a custom launch script (electron-launch) that starts the app with the current working directory and process ID passed as arguments. Requires the source .deb file (my-deb.deb) and the electron-launch script in the files/ directory. ```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 ``` ```sh #!/bin/sh exec "$@" --executed-from="$(pwd)" --pid=$$ > /dev/null 2>&1 & ``` -------------------------------- ### Verify Node.js and npm installation Source: https://github.com/discord/electron/blob/main/docs/tutorial/development-environment.md Run these commands in Terminal to confirm that Node.js and npm are installed correctly. ```sh node --version npm --version ```