tray.popUpContextMenu() method
tray.popUpContextMenu([menu, position]) pops up the context menu of the tray icon on macOS and Windows. menu is an optional Menu object; when passed, this menu is shown instead of the tray icon's context menu. position is an optional Point object for the pop up position. The position is only available on Windows and defaults to (0, 0).
tray.closeContextMenu() method
tray.closeContextMenu() closes an open context menu as set by tray.setContextMenu() on macOS and Windows.
Tray constructor
new Tray(image, [guid]) creates a new tray icon associated with the image. image is a NativeImage or string (required). guid is an optional string that must adhere to UUID format and is only used on Windows and macOS to uniquely identify the tray icon.
tray.getGUID() method
tray.getGUID() returns a string or null on macOS and Windows. It returns the GUID used to uniquely identify the tray icon and allow it to retain its position between relaunches, or null if none is set.
tray.getBounds() method
tray.getBounds() returns a Rectangle object representing the bounds of the tray icon on macOS and Windows.
tray.setContextMenu() method
tray.setContextMenu(menu) sets the context menu for the tray icon. menu is a Menu object or null.
tray.isDestroyed() method
tray.isDestroyed() returns a boolean indicating whether the tray icon is destroyed.
tray.destroy() method
tray.destroy() destroys the tray icon immediately.
tray.setPressedImage() method
tray.setPressedImage(image) sets the image associated with the tray icon when pressed on macOS. image is a NativeImage or string.
UtilityProcess.kill method
child.kill() terminates the process gracefully. On POSIX, it uses SIGTERM but ensures the process is reaped on exit. Returns boolean: true if the kill is successful, false otherwise.
utilityProcess.fork requires app ready event
utilityProcess.fork can only be called after the ready event has been emitted on the app.
utilityProcess.fork method signature
utilityProcess.fork(modulePath[, args][, options]) creates a child process. modulePath is a required string path to the script that should run as entrypoint in the child process. args is an optional string[] list of string arguments available as process.argv in the child process. Returns a UtilityProcess instance.
utilityProcess.fork options: env, execArgv, cwd
utilityProcess.fork accepts these options: env (Object, optional) sets environment key-value pairs with default process.env; execArgv (string[], optional) is a list of string arguments passed to the executable; cwd (string, optional) sets the current working directory of the child process.
utilityProcess.fork options: session and partition
utilityProcess.fork accepts session option (Session, optional) which sets the session used by the process for network requests, enabling HTTP caching and session-specific network features; partition option (string, optional) sets the session according to partition string. If partition starts with 'persist:', uses persistent session available to all pages with the same partition. Without 'persist:' prefix, uses in-memory session. Multiple processes can share the same session by assigning same partition. If session option is set, partition is ignored.
utilityProcess.fork options: stdio
utilityProcess.fork stdio option (string[] | string, optional) configures stdout and stderr mode of child process. Default is 'inherit'. String value can be 'pipe', 'ignore', or 'inherit'. Currently only stdout and stderr configuration is supported; stdin must be 'ignore'. Processing: 'pipe' equals ['ignore', 'pipe', 'pipe']; 'ignore' equals ['ignore', 'ignore', 'ignore']; 'inherit' equals ['ignore', 'inherit', 'inherit']. Configuring stdin to anything other than 'ignore' results in an error.
utilityProcess.fork options: serviceName
utilityProcess.fork serviceName option (string, optional) sets the name of the process that appears in the name property of ProcessMetric returned by app.getAppMetrics() and child-process-gone event of app. Default is 'Node Utility Process'.
utilityProcess.fork options: allowLoadingUnsignedLibraries (macOS)
utilityProcess.fork allowLoadingUnsignedLibraries option (boolean, optional, macOS only) when enabled launches the utility process via the Electron Helper (Plugin).app helper executable on macOS, which can be codesigned with com.apple.security.cs.disable-library-validation and com.apple.security.cs.allow-unsigned-executable-memory entitlements. This allows the utility process to load unsigned libraries. Default is false. It is best to leave this disabled unless specifically needed.
utilityProcess.fork options: disclaim (macOS)
utilityProcess.fork disclaim option (boolean, optional, macOS only) when enabled causes the utility process to disclaim responsibility for the child process. This makes the operating system consider the child process as a separate entity for security policies like Transparency, Consent, and Control (TCC). When responsibility is disclaimed, the parent process is not attributed for any TCC requests initiated by the child process. This is useful when launching processes that run third-party or untrusted code. Default is false.
utilityProcess.fork options: respondToAuthRequestsFromMainProcess
utilityProcess.fork respondToAuthRequestsFromMainProcess option (boolean, optional) when enabled allows all HTTP 401 and 407 network requests created via the net module to be responded to via the login event on the UtilityProcess instance when a session is provided, or via app#login event in main process when using default system network context. This option also routes client-certificate selection to app#select-client-certificate event in main process. Without this flag, net requests from utility process proceed without client certificate. Default is false.
UtilityProcess.postMessage method
child.postMessage(message, [transfer]) sends a message to the child process. message parameter is any type (required). transfer parameter is an optional MessagePortMain[] array for transferring ownership of zero or more MessagePortMain objects.
UtilityProcess.postMessage example
// Main process
const { port1, port2 } = new MessageChannelMain()
const child = utilityProcess.fork(path.join(__dirname, 'test.js'))
child.postMessage({ message: 'hello' }, [port1])
// Child process
process.parentPort.once('message', (e) => {
const [port] = e.ports
// ...
})
This example shows sending a message with a transferred MessagePortMain from main process to child process.
WebContentsView constructor options
WebContentsView constructor accepts an optional options object with the following properties: webPreferences (optional, WebPreferences type) - Settings of web page's features; webContents (optional, WebContents type) - If present, the given WebContents will be adopted by the WebContentsView. A WebContents may only be presented in one WebContentsView at a time.
View setBorderRadius method
view.setBorderRadius(radius) sets the border radius. Parameter: radius (Integer, required) is the border radius size in pixels. Note that the area cutout of the view's border still captures clicks.
View setBackgroundBlur method
view.setBackgroundBlur(blurRadius) sets the background blur effect. Parameter: blurRadius (Integer, required) is the radius of the background blur effect in pixels. Note: you must set a background color with an alpha channel (e.g. #80ffffff) in order for the blur effect to be visible.
View setVisible method
view.setVisible(visible) controls view visibility. Parameter: visible (boolean, required) - if false, the view will be hidden from display.
View getVisible method
view.getVisible() returns a boolean indicating whether the view should be drawn. Note that this is different from whether the view is visible on screen—it may still be obscured or out of view.
View constructor
new View() creates a new View instance.
View addChildView method
view.addChildView(view[, index]) adds a child view. Parameters: view (View, required) is the child view to add; index (Integer, optional) is the index at which to insert the child view, defaulting to adding the child at the end of the child list. If the same View is added to a parent which already contains it, it will be reordered such that it becomes the topmost view.
View removeChildView method
view.removeChildView(view) removes a child view. Parameter: view (View, required) is the child view to remove. If the view passed as a parameter is not a child of this view, this method is a no-op.
View setBounds method
view.setBounds(bounds[, options]) sets the bounds of the View. Parameters: bounds (Rectangle, required) is the new bounds of the View; options (Object, optional) can contain animate (boolean or Object, optional) - if true, the bounds change will be animated, or if an object, can contain duration (Integer, optional, default 250 milliseconds) and easing (string, optional, default 'linear') with values: 'linear', 'ease-in', 'ease-out', 'ease-in-out'.
View setBackgroundColor method color formats
view.setBackgroundColor(color) sets the background color. Valid formats are: Hex (#fff, #ffff, #ffffff, #ffffffff where AARRGGBB or ARGB format is used, not RRGGBBAA or RGB); RGB (rgb(255, 255, 255)); RGBA (rgba(255, 255, 255, 1.0)); HSL (hsl(200, 20%, 50%)); HSLA (hsla(200, 20%, 50%, 0.5)); Color names as listed in SkParseColor.cpp, case-sensitive (e.g. blueviolet, red).
View getBounds method
view.getBounds() returns a Rectangle representing the bounds of the View, relative to its parent.
frame.collectJavaScriptCallStack() method
frame.collectJavaScriptCallStack() is an experimental method that returns Promise<string> | Promise<void>. It resolves with the currently running JavaScript call stack. If no JavaScript runs in the frame, the promise will never resolve. In cases where the call stack is otherwise unable to be collected, it will return undefined. This can be useful to determine why the frame is unresponsive in cases where there is long-running JavaScript. The feature requires the enable-features command line switch with 'DocumentPolicyIncludeJSCallStacksInCrashReports'.
webFrameMain usage example with did-frame-navigate
Example showing how to use webFrameMain.fromId() with did-frame-navigate event:
```js
const { BrowserWindow, webFrameMain } = require('electron')
const win = new BrowserWindow({ width: 800, height: 1500 })
win.loadURL('https://twitter.com')
win.webContents.on(
'did-frame-navigate',
(event, url, httpResponseCode, httpStatusText, isMainFrame, frameProcessId, frameRoutingId) => {
const frame = webFrameMain.fromId(frameProcessId, frameRoutingId)
if (frame) {
const code = 'document.body.innerHTML = document.body.innerHTML.replaceAll("heck", "h*ck")'
frame.executeJavaScript(code)
}
}
)
```
webFrameMain accessing frames via WebContents mainFrame
Example showing how to access frames of existing pages using the mainFrame property of WebContents:
```js
const { BrowserWindow } = require('electron')
async function main () {
const win = new BrowserWindow({ width: 800, height: 600 })
await win.loadURL('https://reddit.com')
const youtubeEmbeds = win.webContents.mainFrame.frames.filter((frame) => {
try {
const url = new URL(frame.url)
return url.host === 'www.youtube.com'
} catch {
return false
}
})
console.log(youtubeEmbeds)
}
main()
```
frame.collectJavaScriptCallStack() example
Example showing how to use collectJavaScriptCallStack() to debug unresponsive frames:
```js
const { app } = require('electron')
app.commandLine.appendSwitch('enable-features', 'DocumentPolicyIncludeJSCallStacksInCrashReports')
app.on('web-contents-created', (_, webContents) => {
webContents.on('unresponsive', async () => {
// Interrupt execution and collect call stack from unresponsive renderer
const callStack = await webContents.mainFrame.collectJavaScriptCallStack()
console.log('Renderer unresponsive\n', callStack)
})
})
```
frame.printToPDF() example for iframe
Example showing how to print an iframe to PDF:
```js
const { app, BrowserWindow } = require('electron')
const fs = require('node:fs')
const os = require('node:os')
const path = require('node:path')
app.whenReady().then(() => {
const win = new BrowserWindow()
win.loadFile('page-with-iframe.html')
win.webContents.on('did-finish-load', () => {
const pdfPath = path.join(os.homedir(), 'Desktop', 'iframe.pdf')
const iframe = win.webContents.mainFrame.frames[0]
iframe.printToPDF({}).then(data => {
fs.writeFile(pdfPath, data, (error) => {
if (error) throw error
console.log(`Wrote PDF successfully to ${pdfPath}`)
})
}).catch(error => {
console.log(`Failed to write PDF to ${pdfPath}: `, error)
})
})
})
```
webFrameMain.fromId() method
webFrameMain.fromId(processId, routingId) takes two integer parameters: processId (the internal ID of the process which owns the frame) and routingId (the unique frame ID in the current renderer process). Routing IDs can be retrieved from WebFrameMain instances and are passed by frame-specific WebContents navigation events like did-frame-navigate. Returns WebFrameMain | undefined, or undefined if there is no WebFrameMain associated with the given IDs.
webFrameMain.fromFrameToken() method
webFrameMain.fromFrameToken(processId, frameToken) takes an integer processId (the internal ID of the process which owns the frame) and a string frameToken (a token identifying the unique frame). The frameToken can also be retrieved in the renderer process via webFrame.frameToken. Returns WebFrameMain | null, or null if there is no WebFrameMain associated with the given IDs.
frame.reload() method
frame.reload() returns boolean indicating whether the reload was initiated successfully. Returns false only when the frame has no history.
frame.isDestroyed() method
frame.isDestroyed() returns boolean indicating whether the frame is destroyed.
frame.printToPDF() method
frame.printToPDF(options) prints the frame's web page as PDF. Parameters: options (PrintToPDFOptions). Returns Promise<Buffer> that resolves with the generated PDF data. Unlike webContents.printToPDF(), this method prints only the contents of the frame it is called on, which can be used to print an individual <iframe> from the main process. The landscape option will be ignored if @page CSS at-rule is used in the web page.
webFrame.getWordSuggestions(word)
Returns a string[] array of suggested words for the word string parameter. If the word is spelled correctly, the result will be empty.
webFrame.getResourceUsage example
const { webFrame } = require('electron')
console.log(webFrame.getResourceUsage())
webFrame example zooming to 200%
const { webFrame } = require('electron')
webFrame.setZoomFactor(2)
webFrame.isWordMisspelled(word)
Returns a boolean indicating whether the word string parameter is misspelled according to the built in spellchecker. Returns false if no dictionary is loaded or if the word is spelled correctly.
webFrame.setSpellCheckProvider example with node-spellchecker
const { webFrame } = require('electron')
const spellChecker = require('spellchecker')
webFrame.setSpellCheckProvider('en-US', {
spellCheck (words, callback) {
setTimeout(() => {
const misspelled = words.filter(x => spellchecker.isMisspelled(x))
callback(misspelled)
}, 0)
}
})
webFrame.getZoomLevel()
Returns a number representing the current zoom level.
webFrame.setVisualZoomLevelLimits(minimumLevel, maximumLevel)
Sets the maximum and minimum pinch-to-zoom level. Visual zoom is disabled by default in Electron. To re-enable it, call webFrame.setVisualZoomLevelLimits(1, 3). Visual zoom only applies to pinch-to-zoom behavior. Cmd+/-/0 zoom shortcuts are controlled by the 'zoomIn', 'zoomOut', and 'resetZoom' MenuItem roles in the application Menu.
webFrame.setSpellCheckProvider(language, provider)
Sets a provider for spell checking in input fields and text areas. The language parameter is a string. The provider parameter is an Object with a spellCheck method that accepts an array of individual words (string[]) and a callback function. The callback function is called with an array of misspelt words (string[]). If you want to use this method you must disable the builtin spellchecker when you construct the window by setting webPreferences.spellcheck to false.
webFrame.insertCSS(css[, options])
Injects CSS into the current web page and returns a unique string key for the inserted stylesheet that can later be used to remove the CSS via webFrame.removeInsertedCSS(key). The css parameter is a string. The options parameter is an optional Object with cssOrigin property (optional string, can be 'user' or 'author', sets the cascade origin of the inserted stylesheet, default is 'author').
webFrame.removeInsertedCSS(key)
Removes the inserted CSS from the current web page. The stylesheet is identified by its key, which is returned from webFrame.insertCSS(css).
webFrame.insertText(text)
Inserts the text string to the focused element.
webFrame.executeJavaScript(code[, userGesture][, callback])
Evaluates the code string in the page and returns a Promise<any> that resolves with the result of the executed code or is rejected if execution throws or results in a rejected promise. The userGesture parameter is an optional boolean (default is false) that, when true, will remove the limitation that some HTML APIs like requestFullScreen can only be invoked by a gesture from the user. The callback parameter is an optional Function called after script has been executed with parameters: result (Any) and error (Error). Unless the frame is suspended (e.g. showing a modal alert), execution will be synchronous and the callback will be invoked before the method returns.
webFrame.executeJavaScriptInIsolatedWorld(worldId, scripts[, userGesture][, callback])
Works like executeJavaScript but evaluates scripts in an isolated context. Returns a Promise<any> that resolves with the result of the executed code or is rejected if execution could not start. The worldId parameter is an Integer representing the ID of the world to run the javascript in (0 is the default main world where content runs, 999 is the world used by Electron's contextIsolation feature, accepts values in the range 1..536870911). The scripts parameter is a WebSource[] array. The userGesture parameter is an optional boolean (default is false). The callback parameter is an optional Function with parameters result (Any) and error (Error). When the execution of script fails, the returned promise will not reject and the result would be undefined because Chromium does not dispatch errors of isolated worlds to foreign worlds.
webFrame.setIsolatedWorldInfo(worldId, info)
Set the security origin, content security policy and name of the isolated world. The worldId parameter is an Integer (0 is the default world, 999 is the world used by Electron's contextIsolation feature, Chrome extensions reserve the range [1 << 20, 1 << 29)). The info parameter is an Object with optional properties: securityOrigin (string), csp (string), and name (string). If the csp is specified, then the securityOrigin also has to be specified.
webFrame.getIsolatedWorlds()
Returns an Integer[] of the IDs of isolated worlds that currently exist for this frame. This does not include the main world (ID 0) or Electron's preload world (ID 999). This can be used to discover existing isolated worlds before calling APIs such as webFrame.executeJavaScriptInIsolatedWorld(...) or contextBridge.exposeInIsolatedWorld(...).
webFrame.getResourceUsage()
Returns an Object describing usage information of Blink's internal memory caches with the following properties: images (MemoryUsageDetails), scripts (MemoryUsageDetails), cssStyleSheets (MemoryUsageDetails), xslStyleSheets (MemoryUsageDetails), fonts (MemoryUsageDetails), and other (MemoryUsageDetails). Each MemoryUsageDetails object contains count, size, and liveSize properties.
webFrame.clearCache()
Attempts to free memory that is no longer being used (like images from a previous navigation). Blindly calling this method probably makes Electron slower since it will have to refill these emptied caches, so you should only call it if an event in your app has occurred that makes you think your page is actually using less memory.
webFrame.getFrameForSelector(selector)
Returns a WebFrame | null representing the frame element in webFrame's document selected by the selector string parameter. Returns null if selector does not select a frame or if the frame is not in the current renderer process.