processId Integer – An Integer representing the internal ID of the process which owns the frame.
routingId Integer – An Integer representing the unique frame ID in the current renderer process. Routing IDs can be retrieved from WebFrameMain instances (frame.routingId) and are also passed by frame specific WebContents navigation events (e.g. did-frame-navigate).
Returns WebFrameMain | undefined – A frame with the given process and routing IDs, or undefined if there is no WebFrameMain associated with the given IDs.
userGesture boolean (optional) – Default is false.
Returns Promise<unknown> – A promise that resolves with the result of the executed code or is rejected if execution throws or results in a rejected promise.
Evaluates code in page.
In the browser window some HTML APIs like requestFullScreen can only be invoked by a gesture from the user. Setting userGesture to true will remove this limitation.
Send an asynchronous message to the renderer process via channel, along with arguments. Arguments will be serialized with the Structured Clone Algorithm, just like postMessage, so prototype chains will not be included. Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will throw an exception.
The renderer process can handle the message by listening to channel with the ipcRenderer module.
Send a message to the renderer process, optionally transferring ownership of zero or more MessagePortMain objects.
The transferred MessagePortMain objects will be available in the renderer process by accessing the ports property of the emitted event. When they arrive in the renderer, they will be native DOM MessagePort objects.
For example:
// Main process const win = new BrowserWindow() const { port1, port2 } = new MessageChannelMain() win.webContents.mainFrame.postMessage('port', { message: 'hello' }, [port1])
IPC messages sent with ipcRenderer.send, ipcRenderer.sendSync or ipcRenderer.postMessage will be delivered in the following order:
contents.on('ipc-message')
contents.mainFrame.on(channel)
contents.ipc.on(channel)
ipcMain.on(channel)
Handlers registered with invoke will be checked in the following order. The first one that is defined will be called, the rest will be ignored.
contents.mainFrame.handle(channel)
contents.handle(channel)
ipcMain.handle(channel)
In most cases, only the main frame of a WebContents can send or receive IPC messages. However, if the nodeIntegrationInSubFrames option is enabled, it is possible for child frames to send and receive IPC messages also. The WebContents.ipc interface may be more convenient when nodeIntegrationInSubFrames is not enabled.
A string representing the current origin of the frame, serialized according to RFC 6454. This may be different from the URL. For instance, if the frame is a child window opened to about:blank, then frame.origin will return the parent frame’s origin, while frame.url will return the empty string. Pages without a scheme/host/port triple origin will have the serialized origin of "null" (that is, the string containing the letters n, u, l, l).
An Integer representing the id of the frame’s internal FrameTreeNode instance. This id is browser-global and uniquely identifies a frame that hosts content. The identifier is fixed at the creation of the frame and stays constant for the lifetime of the frame. When the frame is removed, the id is not used again.
An Integer representing the Chromium internal pid of the process which owns this frame. This is not the same as the OS process ID; to read that use frame.osProcessId.
An Integer representing the unique frame id in the current renderer process. Distinct WebFrameMain instances that refer to the same underlying frame will have the same routingId.
webPreferencesWebPreferences (optional) – Settings of web page’s features.
webContentsWebContents (optional) – If present, the given WebContents will be adopted by the WebContentsView. A WebContents may only be presented in one WebContentsView at a time.
webContents is an EventEmitter. It is responsible for rendering and controlling a web page and is a property of the BrowserWindow object. An example of accessing the webContents object:
In-page navigations don’t cause the page to reload, but instead navigate to a location within the current page. These events are not cancellable. For an in-page navigations, the following events will fire in this order:
Returns WebContents[] – An array of all WebContents instances. This will contain web contents for all windows, webviews, opened devtools, and devtools extension background pages.
Returns WebContents | undefined – A WebContents instance with the given WebFrameMain, or undefined if there is no WebContents associated with the given WebFrameMain.
targetId string – The Chrome DevTools Protocol TargetID associated with the WebContents instance.
Returns WebContents | undefined – A WebContents instance with the given TargetID, or undefined if there is no WebContents associated with the given TargetID.
When communicating with the Chrome DevTools Protocol, it can be useful to lookup a WebContents instance based on its assigned TargetID.
frameName string – Name given to the created window in the window.open() call.
optionsBrowserWindowConstructorOptions – The options used to create the BrowserWindow. They are merged in increasing precedence: parsed options from the features string from window.open(), security-related webPreferences inherited from the parent, and options given by webContents.setWindowOpenHandler. Unrecognized options are not filtered out.
referrerReferrer – The referrer that will be passed to the new window. May or may not result in the Referer header being sent, depending on the referrer policy.
postBodyPostBody (optional) – The post data that will be sent to the new window, along with the appropriate headers that will be set. If no post data is to be sent, the value will be null. Only defined when the window is being created by a form that set target=_blank.
disposition string – Can be default, foreground-tab, background-tab, new-window or other.
Emitted after successful creation of a window via window.open in the renderer. Not emitted if the creation of the window is canceled from webContents.setWindowOpenHandler.
See window.open() for more details and how to use this in conjunction with webContents.setWindowOpenHandler.
isSameDocument boolean – This event does not fire for same document navigations using window.history api and reference fragment navigations. This property is always set to false for this event.
isMainFrame boolean – True if the navigation is taking place in a main frame.
frame WebFrameMain – The frame to be navigated.
initiator WebFrameMain (optional) – The frame which initiated the navigation, which can be a parent frame (e.g. via window.open with a frame’s name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted.
url string Deprecated
isInPlace boolean Deprecated
isMainFrame boolean Deprecated
frameProcessId Integer Deprecated
frameRoutingId Integer Deprecated
Emitted when a user or the page wants to start navigation on the main frame. It can happen when the window.location object is changed or a user clicks a link in the page.
This event will not emit when the navigation is started programmatically with APIs like webContents.loadURL and webContents.back.
It is also not emitted for in-page navigations, such as clicking anchor links or updating the window.location.hash. Use did-navigate-in-page event for this purpose.
Calling event.preventDefault() will prevent the navigation.
isSameDocument boolean – This event does not fire for same document navigations using window.history api and reference fragment navigations. This property is always set to false for this event.
isMainFrame boolean – True if the navigation is taking place in a main frame.
frame WebFrameMain – The frame to be navigated.
initiator WebFrameMain (optional) – The frame which initiated the navigation, which can be a parent frame (e.g. via window.open with a frame’s name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted.
Emitted when a user or the page wants to start navigation in any frame. It can happen when the window.location object is changed or a user clicks a link in the page.
Unlike will-navigate, will-frame-navigate is fired when the main frame or any of its subframes attempts to navigate. When the navigation event comes from the main frame, isMainFrame will be true.
This event will not emit when the navigation is started programmatically with APIs like webContents.loadURL and webContents.back.
It is also not emitted for in-page navigations, such as clicking anchor links or updating the window.location.hash. Use did-navigate-in-page event for this purpose.
Calling event.preventDefault() will prevent the navigation.
isSameDocument boolean – Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation.
isMainFrame boolean – True if the navigation is taking place in a main frame.
frame WebFrameMain – The frame to be navigated.
initiator WebFrameMain (optional) – The frame which initiated the navigation, which can be a parent frame (e.g. via window.open with a frame’s name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted.
url string Deprecated
isInPlace boolean Deprecated
isMainFrame boolean Deprecated
frameProcessId Integer Deprecated
frameRoutingId Integer Deprecated
Emitted when any frame (including main) starts navigating.
isSameDocument boolean – Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation.
isMainFrame boolean – True if the navigation is taking place in a main frame.
frame WebFrameMain – The frame to be navigated.
initiator WebFrameMain (optional) – The frame which initiated the navigation, which can be a parent frame (e.g. via window.open with a frame’s name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted.
url string Deprecated
isInPlace boolean Deprecated
isMainFrame boolean Deprecated
frameProcessId Integer Deprecated
frameRoutingId Integer Deprecated
Emitted when a server side redirect occurs during navigation. For example a 302 redirect.
This event will be emitted after did-start-navigation and always before the did-redirect-navigation event for the same navigation.
Calling event.preventDefault() will prevent the navigation (not just the redirect).
isSameDocument boolean – Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation.
isMainFrame boolean – True if the navigation is taking place in a main frame.
frame WebFrameMain – The frame to be navigated.
initiator WebFrameMain (optional) – The frame which initiated the navigation, which can be a parent frame (e.g. via window.open with a frame’s name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted.
url string Deprecated
isInPlace boolean Deprecated
isMainFrame boolean Deprecated
frameProcessId Integer Deprecated
frameRoutingId Integer Deprecated
Emitted after a server side redirect occurs during navigation. For example a 302 redirect.
This event cannot be prevented, if you want to prevent redirects you should checkout out the will-redirect event above.
httpResponseCode Integer – -1 for non HTTP navigations
httpStatusText string – empty for non HTTP navigations
Emitted when a main frame navigation is done.
This event is not emitted for in-page navigations, such as clicking anchor links or updating the window.location.hash. Use did-navigate-in-page event for this purpose.
httpResponseCode Integer – -1 for non HTTP navigations
httpStatusText string – empty for non HTTP navigations,
isMainFrame boolean
frameProcessId Integer
frameRoutingId Integer
Emitted when any frame navigation is done.
This event is not emitted for in-page navigations, such as clicking anchor links or updating the window.location.hash. Use did-navigate-in-page event for this purpose.
Emitted when an in-page navigation happened in any frame.
When in-page navigation happens, the page URL changes but does not cause navigation outside of the page. Examples of this occurring are when anchor links are clicked or when the DOM hashchange event is triggered.
Emitted when a beforeunload event handler is attempting to cancel a page unload.
Calling event.preventDefault() will ignore the beforeunload event handler and allow the page to be unloaded.
const { BrowserWindow, dialog } = require('electron') const win = new BrowserWindow({ width: 800, height: 600 }) win.webContents.on('will-prevent-unload', (event) => { const choice = dialog.showMessageBoxSync(win, { type: 'question', buttons: ['Leave', 'Stay'], title: 'Do you want to leave this site?', message: 'Changes you made may not be saved.', defaultId: 0, cancelId: 1 }) const leave = (choice === 0) if (leave) { event.preventDefault() } })
Note: This will be emitted for BrowserViews but will not be respected – this is because we have chosen not to tie the BrowserView lifecycle to its owning BrowserWindow should one exist per the specification.
Emitted before dispatching the keydown and keyup events in the page. Calling event.preventDefault will prevent the page keydown/keyup events and the menu shortcuts.
const win = new BrowserWindow({ width: 800, height: 600 })
win.webContents.on('before-input-event', (event, input) => { // For example, only enable application menu keyboard shortcuts when // Ctrl/Cmd are down. win.webContents.setIgnoreMenuShortcuts(!input.control && !input.meta) })
Note that on macOS, having focus means the WebContents is the first responder of window, so switching focus between windows would not trigger the focus and blur events of WebContents, as the first responder of each window is not changed.
The focus and blur events of WebContents should only be used to detect focus change between different WebContents and BrowserView in the same window.
hotspotPoint (optional) – coordinates of the custom cursor’s hotspot.
Emitted when the cursor’s type changes. The type parameter can be pointer, crosshair, hand, text, wait, help, e-resize, n-resize, ne-resize, nw-resize, s-resize, se-resize, sw-resize, w-resize, ns-resize, ew-resize, nesw-resize, nwse-resize, col-resize, row-resize, m-panning, m-panning-vertical, m-panning-horizontal, e-panning, n-panning, ne-panning, nw-panning, s-panning, se-panning, sw-panning, w-panning, move, vertical-text, cell, context-menu, alias, progress, nodrop, copy, none, not-allowed, zoom-in, zoom-out, grab, grabbing, custom, null, drag-drop-none, drag-drop-move, drag-drop-copy, drag-drop-link, ns-no-resize, ew-no-resize, nesw-no-resize, nwse-no-resize, or default.
If the type parameter is custom, the image parameter will hold the custom cursor image in a NativeImage, and scale, size and hotspot will hold additional information about the custom cursor.
frame WebFrameMain – Frame from which the context menu was invoked.
linkURL string – URL of the link that encloses the node the context menu was invoked on.
linkText string – Text associated with the link. May be an empty string if the contents of the link are an image.
pageURL string – URL of the top level page that the context menu was invoked on.
frameURL string – URL of the subframe that the context menu was invoked on.
srcURL string – Source URL for the element that the context menu was invoked on. Elements with source URLs are images, audio and video.
mediaType string – Type of the node the context menu was invoked on. Can be none, image, audio, video, canvas, file or plugin.
hasImageContents boolean – Whether the context menu was invoked on an image which has non-empty contents.
isEditable boolean – Whether the context is editable.
selectionText string – Text of the selection that the context menu was invoked on.
titleText string – Title text of the selection that the context menu was invoked on.
altText string – Alt text of the selection that the context menu was invoked on.
suggestedFilename string – Suggested filename to be used when saving file through ‘Save Link As’ option of context menu.
selectionRectRectangle – Rect representing the coordinates in the document space of the selection.
selectionStartOffset number – Start position of the selection text.
referrerPolicyReferrer – The referrer policy of the frame on which the menu is invoked.
misspelledWord string – The misspelled word under the cursor, if any.
dictionarySuggestions string[] – An array of suggested words to show the user to replace the misspelledWord. Only available if there is a misspelled word and spellchecker is enabled.
frameCharset string – The character encoding of the frame on which the menu was invoked.
formControlType string – The source that the context menu was invoked on. Possible values include none, button-button, field-set, input-button, input-checkbox, input-color, input-date, input-datetime-local, input-email, input-file, input-hidden, input-image, input-month, input-number, input-password, input-radio, input-range, input-reset, input-search, input-submit, input-telephone, input-text, input-time, input-url, input-week, output, reset-button, select-list, select-list, select-multiple, select-one, submit-button, and text-area,
spellcheckEnabled boolean – If the context is editable, whether or not spellchecking is enabled.
menuSourceType string – Input source that invoked the context menu. Can be none, mouse, keyboard, touch, touchMenu, longPress, longTap, touchHandle, stylus, adjustSelection, or adjustSelectionReset.
mediaFlags Object – The flags for the media element the context menu was invoked on.
inError boolean – Whether the media element has crashed.
isPaused boolean – Whether the media element is paused.
isMuted boolean – Whether the media element is muted.
hasAudio boolean – Whether the media element has audio.
isLooping boolean – Whether the media element is looping.
isControlsVisible boolean – Whether the media element’s controls are visible.
canToggleControls boolean – Whether the media element’s controls are toggleable.
canPrint boolean – Whether the media element can be printed.
canSave boolean – Whether or not the media element can be downloaded.
canShowPictureInPicture boolean – Whether the media element can show picture-in-picture.
isShowingPictureInPicture boolean – Whether the media element is currently showing picture-in-picture.
canRotate boolean – Whether the media element can be rotated.
canLoop boolean – Whether the media element can be looped.
editFlags Object – These flags indicate whether the renderer believes it is able to perform the corresponding action.
canUndo boolean – Whether the renderer believes it can undo.
canRedo boolean – Whether the renderer believes it can redo.
canCut boolean – Whether the renderer believes it can cut.
canCopy boolean – Whether the renderer believes it can copy.
canPaste boolean – Whether the renderer believes it can paste.
canDelete boolean – Whether the renderer believes it can delete.
canSelectAll boolean – Whether the renderer believes it can select all.
canEditRichly boolean – Whether the renderer believes it can edit text richly.
Emitted when there is a new context menu that needs to be handled.
Emitted when a bluetooth device needs to be selected when a call to navigator.bluetooth.requestDevice is made. callback should be called with the deviceId of the device to be selected. Passing an empty string to callback will cancel the request.
If an event listener is not added for this event, or if event.preventDefault is not called when handling this event, the first available device will be automatically selected.
Due to the nature of bluetooth, scanning for devices when navigator.bluetooth.requestDevice is called may take time and will cause select-bluetooth-device to fire multiple times until callback is called with either a device id or an empty string to cancel the request.
app.whenReady().then(() => { win = new BrowserWindow({ width: 800, height: 600 }) win.webContents.on('select-bluetooth-device', (event, deviceList, callback) => { event.preventDefault() const result = deviceList.find((device) => { return device.deviceName === 'test' }) if (!result) { // The device wasn't found so we need to either wait longer (eg until the // device is turned on) or cancel the request by calling the callback // with an empty string. callback('') } else { callback(result.deviceId) } }) })
webPreferencesWebPreferences – The web preferences that will be used by the guest page. This object can be modified to adjust the preferences for the guest page.
params Record<string, string> – The other <webview> parameters such as the src URL. This object can be modified to adjust the parameters of the guest page.
Emitted when a <webview>‘s web contents is being attached to this web contents. Calling event.preventDefault() will destroy the guest page.
This event can be used to configure webPreferences for the webContents of a <webview> before it’s loaded, and provides the ability to set settings that can’t be set via <webview> attributes.
baseURLForDataURL string (optional) – Base url (with trailing path separator) for files to be loaded by the data url. This is needed only if the specified url is a data url and needs to load other files.
Returns Promise<void> – the promise will resolve when the page has finished loading (see did-finish-load), and rejects if the page fails to load (see did-fail-load). A noop rejection handler is already attached, which avoids unhandled rejection errors.
Loads the url in the window. The url must contain the protocol prefix, e.g. the http:// or file://. If the load should bypass http cache then use the pragma header to achieve it.
query Record<string, string> (optional) – Passed to url.format().
search string (optional) – Passed to url.format().
hash string (optional) – Passed to url.format().
Returns Promise<void> – the promise will resolve when the page has finished loading (see did-finish-load), and rejects if the page fails to load (see did-fail-load).
Loads the given file in the window, filePath should be a path to an HTML file relative to the root of your application. For instance an app structure like this:
waitForBeforeUnload boolean – if true, fire the beforeunload event before closing the page. If the page prevents the unload, the WebContents will not be closed. The will-prevent-unload will be fired if the page requests prevention of unload.
Closes the page, as if the web content had called window.close().
If the page is successfully closed (i.e. the unload is not prevented by the page, or waitForBeforeUnload is false or unspecified), the WebContents will be destroyed and no longer usable. The destroyed event will be emitted.
Forcefully terminates the renderer process that is currently hosting this webContents. This will cause the render-process-gone event to be emitted with the reason=killed || reason=crashed. Please note that some webContents share renderer processes and therefore calling this method may also crash the host process for other webContents as well.
Calling reload() immediately after calling this method will force the reload to occur in a new process. This should be used when this process is unstable or unusable, for instance in order to recover from the unresponsive event.
const win = new BrowserWindow()
win.webContents.on('unresponsive', async () => { const { response } = await dialog.showMessageBox({ message: 'App X has become unresponsive', title: 'Do you want to try forcefully reloading the app?', buttons: ['OK', 'Cancel'], cancelId: 1 }) if (response === 0) { win.webContents.forcefullyCrashRenderer() win.webContents.reload() } })
cssOrigin string (optional) – Can be ‘user’ or ‘author’. Sets the cascade origin of the inserted stylesheet. Default is ‘author’.
Returns Promise<string> – A promise that resolves with a key for the inserted CSS that can later be used to remove the CSS via contents.removeInsertedCSS(key).
Injects CSS into the current web page and returns a unique key for the inserted stylesheet.
const win = new BrowserWindow() win.webContents.on('did-finish-load', () => { win.webContents.insertCSS('html, body { background-color: #f00; }') })
userGesture boolean (optional) – Default is false.
Returns Promise<any> – A promise that resolves with the result of the executed code or is rejected if the result of the code is a rejected promise.
Evaluates code in page.
In the browser window some HTML APIs like requestFullScreen can only be invoked by a gesture from the user. Setting userGesture to true will remove this limitation.
Code execution will be suspended until web page stop loading.
const win = new BrowserWindow()
win.webContents.executeJavaScript('fetch("https://jsonplaceholder.typicode.com/users/1").then(resp => resp.json())', true) .then((result) => { console.log(result) // Will be the JSON object from the fetch call })
worldId Integer – The ID of the world to run the javascript in, 0 is the default world, 999 is the world used by Electron’s contextIsolation feature. You can provide any integer here.
url string – The resolved version of the URL passed to window.open(). e.g. opening a window with window.open('foo') will yield something like https://the-origin/the/current/path/foo.
frameName string – Name of the window provided in window.open()
features string – Comma separated list of window features provided to window.open().
disposition string – Can be default, foreground-tab, background-tab, new-window or other.
referrerReferrer – The referrer that will be passed to the new window. May or may not result in the Referer header being sent, depending on the referrer policy.
postBodyPostBody (optional) – The post data that will be sent to the new window, along with the appropriate headers that will be set. If no post data is to be sent, the value will be null. Only defined when the window is being created by a form that set target=_blank.
Returns WindowOpenHandlerResponse – When set to { action: 'deny' } cancels the creation of the new window. { action: 'allow' } will allow the new window to be created. Returning an unrecognized value such as a null, undefined, or an object without a recognized ‘action’ value will result in a console error and have the same effect as returning {action: 'deny'}.
Called before creating a window a new window is requested by the renderer, e.g. by window.open(), a link with target="_blank", shift+clicking on a link, or submitting a form with <form target="_blank">. See window.open() for more details and how to use this in conjunction with did-create-window.
An example showing how to customize the process of new BrowserWindow creation to be BrowserView attached to main window instead:
Changes the zoom level to the specified level. The original size is 0 and each increment above or below represents zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively. The formula for this is scale := 1.2 ^ level.
NOTE: The zoom policy at the Chromium level is same-origin, meaning that the zoom level for a specific domain propagates across all instances of windows with the same domain. Differentiating the window URLs will make zoom work per-window.
start Number (optional) – Amount to shift the start index of the current selection.
end Number (optional) – Amount to shift the end index of the current selection.
Adjusts the current text selection starting and ending points in the focused frame by the given amounts. A negative amount moves the selection towards the beginning of the document, and a positive amount moves the selection towards the end of the document.
Example:
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 })
For a call of win.webContents.adjustSelection({ start: 1, end: 5 })
text string – Content to be searched, must not be empty.
options Object (optional)
forward boolean (optional) – Whether to search forward or backward, defaults to true.
findNext boolean (optional) – Whether to begin a new text finding session with this request. Should be true for initial requests, and false for follow-up requests. Defaults to false.
matchCase boolean (optional) – Whether search should be case-sensitive, defaults to false.
Returns Integer – The request id used for the request.
Starts a request to find all matches for the text in the web page. The result of the request can be obtained by subscribing to found-in-page event.
rectRectangle (optional) – The area of the page to be captured.
opts Object (optional)
stayHidden boolean (optional) – Keep the page hidden instead of visible. Default is false.
stayAwake boolean (optional) – Keep the system awake instead of allowing it to sleep. Default is false.
Returns Promise<NativeImage> – Resolves with a NativeImage
Captures a snapshot of the page within rect. Omitting rect will capture the whole visible page. The page is considered visible when its browser window is hidden and the capturer count is non-zero. If you would like the page to stay hidden, you should ensure that stayHidden is set to true.
silent boolean (optional) – Don’t ask user for print settings. Default is false.
printBackground boolean (optional) – Prints the background color and image of the web page. Default is false.
deviceName string (optional) – Set the printer device name to use. Must be the system-defined name and not the ‘friendly’ name, e.g ‘Brother_QL_820NWB’ and not ‘Brother QL-820NWB’.
color boolean (optional) – Set whether the printed web page will be in color or grayscale. Default is true.
margins Object (optional)
marginType string (optional) – Can be default, none, printableArea, or custom. If custom is chosen, you will also need to specify top, bottom, left, and right.
top number (optional) – The top margin of the printed web page, in pixels.
bottom number (optional) – The bottom margin of the printed web page, in pixels.
left number (optional) – The left margin of the printed web page, in pixels.
right number (optional) – The right margin of the printed web page, in pixels.
landscape boolean (optional) – Whether the web page should be printed in landscape mode. Default is false.
scaleFactor number (optional) – The scale factor of the web page.
pagesPerSheet number (optional) – The number of pages to print per page sheet.
collate boolean (optional) – Whether the web page should be collated.
copies number (optional) – The number of copies of the web page to print.
pageRanges Object[] (optional) – The page range to print. On macOS, only one range is honored.
from number – Index of the first page to print (0-based).
to number – Index of the last page to print (inclusive) (0-based).
duplexMode string (optional) – Set the duplex mode of the printed web page. Can be simplex, shortEdge, or longEdge.
dpi Record (optional)
horizontal number (optional) – The horizontal dpi.
vertical number (optional) – The vertical dpi.
header string (optional) – string to be printed as page header.
footer string (optional) – string to be printed as page footer.
pageSize string | Size (optional) – Specify page size of the printed document. Can be A0, A1, A2, A3, A4, A5, A6, Legal, Letter, Tabloid or an Object containing height and width.
callback Function (optional)
success boolean – Indicates success of the print call.
failureReason string – Error description called back if the print fails.
When a custom pageSize is passed, Chromium attempts to validate platform specific minimum values for width_microns and height_microns. Width and height must both be minimum 353 microns but may be higher on some operating systems.
Prints window’s web page. When silent is set to true, Electron will pick the system’s default printer if deviceName is empty and the default settings for printing.
Use page-break-before: always; CSS style to force to print to a new page.
Example usage:
const win = new BrowserWindow() const options = { silent: true, deviceName: 'My-Printer', pageRanges: [{ from: 0, to: 1 }] } win.webContents.print(options, (success, errorType) => { if (!success) console.log(errorType) })
landscape boolean (optional) – Paper orientation.true for landscape, false for portrait. Defaults to false.
displayHeaderFooter boolean (optional) – Whether to display header and footer. Defaults to false.
printBackground boolean (optional) – Whether to print background graphics. Defaults to false.
scale number(optional) – Scale of the webpage rendering. Defaults to 1.
pageSize string | Size (optional) – Specify page size of the generated PDF. Can be A0, A1, A2, A3, A4, A5, A6, Legal, Letter, Tabloid, Ledger, or an Object containing height and width in inches. Defaults to Letter.
margins Object (optional)
top number (optional) – Top margin in inches. Defaults to 1cm (~0.4 inches).
bottom number (optional) – Bottom margin in inches. Defaults to 1cm (~0.4 inches).
left number (optional) – Left margin in inches. Defaults to 1cm (~0.4 inches).
right number (optional) – Right margin in inches. Defaults to 1cm (~0.4 inches).
pageRanges string (optional) – Page ranges to print, e.g., ‘1-5, 8, 11-13’. Defaults to the empty string, which means print all pages.
headerTemplate string (optional) – HTML template for the print header. Should be valid HTML markup with following classes used to inject printing values into them: date (formatted print date), title (document title), url (document location), pageNumber (current page number) and totalPages (total pages in the document). For example, <span class=title></span> would generate span containing the title.
footerTemplate string (optional) – HTML template for the print footer. Should use the same format as the headerTemplate.
preferCSSPageSize boolean (optional) – Whether or not to prefer page size as defined by css. Defaults to false, in which case the content will be scaled to fit the paper size.
generateTaggedPDF boolean (optional) Experimental – Whether or not to generate a tagged (accessible) PDF. Defaults to false. As this property is experimental, the generated PDF may not adhere fully to PDF/UA and WCAG standards.
generateDocumentOutline boolean (optional) Experimental – Whether or not to generate a PDF document outline from content headers. Defaults to false.
Returns Promise<Buffer> – Resolves with the generated PDF data.
Prints the window’s web page as PDF.
The landscape will be ignored if @page CSS at-rule is used in the web page.
Uses the devToolsWebContents as the target WebContents to show devtools.
The devToolsWebContents must not have done any navigation, and it should not be used for other purposes after the call.
By default Electron manages the devtools by creating an internal WebContents with native view, which developers have very limited control of. With the setDevToolsWebContents method, developers can use any WebContents to show the devtools in it, including BrowserWindow, BrowserView and <webview> tag.
Note that closing the devtools does not destroy the devToolsWebContents, it is caller’s responsibility to destroy devToolsWebContents.
An example of showing devtools in a <webview> tag:
mode string – Opens the devtools with specified dock state, can be left, right, bottom, undocked, detach. Defaults to last used dock state. In undocked mode it’s possible to dock back. In detach mode it’s not.
activate boolean (optional) – Whether to bring the opened devtools window to the foreground. The default is true.
title string (optional) – A title for the DevTools window (only in undocked or detach mode).
Opens the devtools.
When contents is a <webview> tag, the mode would be detach by default, explicitly passing an empty mode can force using last used dock state.
On Windows, if Windows Control Overlay is enabled, Devtools will be opened with mode: 'detach'.
Send an asynchronous message to the renderer process via channel, along with arguments. Arguments will be serialized with the Structured Clone Algorithm, just like postMessage, so prototype chains will not be included. Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will throw an exception.
WARNING
Sending non-standard JavaScript types such as DOM objects or special Electron objects will throw an exception.
frameId Integer | [number, number] – the ID of the frame to send to, or a pair of [processId, frameId] if the frame is in a different process to the main frame.
channel string
...args any[]
Send an asynchronous message to a specific frame in a renderer process via channel, along with arguments. Arguments will be serialized with the Structured Clone Algorithm, just like postMessage, so prototype chains will not be included. Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will throw an exception.
NOTE: Sending non-standard JavaScript types such as DOM objects or special Electron objects will throw an exception.
The renderer process can handle the message by listening to channel with the ipcRenderer module.
If you want to get the frameId of a given renderer context you should use the webFrame.routingId value. E.g.
// In a renderer process console.log('My frameId is:', require('electron').webFrame.routingId)
You can also read frameId from all incoming IPC messages in the main process.
// In the main process ipcMain.on('ping', (event) => { console.info('Message came from frameId:', event.frameId) })
Send a message to the renderer process, optionally transferring ownership of zero or more MessagePortMain objects.
The transferred MessagePortMain objects will be available in the renderer process by accessing the ports property of the emitted event. When they arrive in the renderer, they will be native DOM MessagePort objects.
For example:
// Main process const win = new BrowserWindow() const { port1, port2 } = new MessageChannelMain() win.webContents.postMessage('port', { message: 'hello' }, [port1])
Begin subscribing for presentation events and captured frames, the callback will be called with callback(image, dirtyRect) when there is a presentation event.
The image is an instance of NativeImage that stores the captured frame.
The dirtyRect is an object with x, y, width, height properties that describes which part of the page was repainted. If onlyDirty is set to true, image will only contain the repainted area. onlyDirty defaults to false.
files string[] (optional) – The paths to the files being dragged. (files will override file field)
iconNativeImage | string – The image must be non-empty on macOS.
Sets the item as dragging item for current drag-drop operation, file is the absolute path of the file to be dragged, and icon is the image showing under the cursor when dragging.
policy string – Specify the WebRTC IP Handling Policy.
default – Exposes user’s public and local IPs. This is the default behavior. When this policy is used, WebRTC has the right to enumerate all interfaces and bind them to discover public interfaces.
default_public_interface_only – Exposes user’s public IP, but does not expose user’s local IP. When this policy is used, WebRTC should only use the default route used by http. This doesn’t expose any local addresses.
default_public_and_private_interfaces – Exposes user’s public and local IPs. When this policy is used, WebRTC should only use the default route used by http. This also exposes the associated default private address. Default route is the route chosen by the OS on a multi-homed endpoint.
disable_non_proxied_udp – Does not expose public or local IPs. When this policy is used, WebRTC should only use TCP to contact peers or servers unless the proxy server supports UDP.
Setting the WebRTC IP handling policy allows you to control which IPs are exposed via WebRTC. See BrowserLeaks for more details.
min Integer – The minimum UDP port number that WebRTC should use.
max Integer – The maximum UDP port number that WebRTC should use.
Setting the WebRTC UDP Port Range allows you to restrict the udp port range used by WebRTC. By default the port range is unrestricted. Note: To reset to an unrestricted port range this value should be set to { min: 0, max: 0 }.
requestWebContents WebContents – Web contents that the id will be registered to.
Returns string – The identifier of a WebContents stream. This identifier can be used with navigator.mediaDevices.getUserMedia using a chromeMediaSource of tab. The identifier is restricted to the web contents that it is registered to and is only valid for 10 seconds.
Returns Integer – The Chromium internal pid of the associated renderer. Can be compared to the frameProcessId passed by frame specific navigation events (e.g. did-frame-navigate)
Returns boolean – whether or not this WebContents will throttle animations and timers when the page becomes backgrounded. This also affects the Page Visibility API.
Controls whether or not this WebContents will throttle animations and timers when the page becomes backgrounded. This also affects the Page Visibility API.
policy string – Can be animate, animateOnce or noAnimation.
Sets the image animation policy for this webContents. The policy only affects new images, existing images that are currently being animated are unaffected. This is a known limitation in Chromium, you can force image animation to be recalculated with img.src = img.src which will result in no network traffic but will update the animation policy.
This corresponds to the animationPolicy accessibility feature in Chromium.
An IpcMain scoped to just IPC messages sent from this WebContents.
IPC messages sent with ipcRenderer.send, ipcRenderer.sendSync or ipcRenderer.postMessage will be delivered in the following order:
contents.on('ipc-message')
contents.mainFrame.on(channel)
contents.ipc.on(channel)
ipcMain.on(channel)
Handlers registered with invoke will be checked in the following order. The first one that is defined will be called, the rest will be ignored.
contents.mainFrame.handle(channel)
contents.handle(channel)
ipcMain.handle(channel)
A handler or event listener registered on the WebContents will receive IPC messages sent from any frame, including child frames. In most cases, only the main frame can send IPC messages. However, if the nodeIntegrationInSubFrames option is enabled, it is possible for child frames to send IPC messages also. In that case, handlers should check the senderFrame property of the IPC event to ensure that the message is coming from the expected frame. Alternatively, register handlers on the appropriate frame directly using the WebFrameMain.ipc interface.
A number property that determines the zoom level for this web contents.
The original size is 0 and each increment above or below represents zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively. The formula for this is scale := 1.2 ^ level.
A boolean property that determines whether or not this WebContents will throttle animations and timers when the page becomes backgrounded. This also affects the Page Visibility API.
utilityProcess creates a child process with Node.js and Message ports enabled. It provides the equivalent of child_process.fork API from Node.js but instead uses Services API from Chromium to launch the child process.
modulePath string – Path to the script that should run as entrypoint in the child process.
args string[] (optional) – List of string arguments that will be available as process.argv in the child process.
options Object (optional)
env Object (optional) – Environment key-value pairs. Default is process.env.
execArgv string[] (optional) – List of string arguments passed to the executable.
cwd string (optional) – Current working directory of the child process.
stdio (string[] | string) (optional) – Allows configuring the mode for stdout and stderr of the child process. Default is inherit. String value can be one of pipe, ignore, inherit, for more details on these values you can refer to stdio documentation from Node.js. Currently this option only supports configuring stdout and stderr to either pipe, inherit or ignore. Configuring stdin to any property other than ignore is not supported and will result in an error. For example, the supported values will be processed as following:
pipe: equivalent to [‘ignore’, ‘pipe’, ‘pipe’]
ignore: equivalent to [‘ignore’, ‘ignore’, ‘ignore’]
inherit: equivalent to [‘ignore’, ‘inherit’, ‘inherit’] (the default)
allowLoadingUnsignedLibraries boolean (optional) macOS – With this flag, the utility process will be launched 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 will allow the utility process to load unsigned libraries. Unless you specifically need this capability, it is best to leave this disabled. Default is false.
Terminates the process gracefully. On POSIX, it uses SIGTERM but will ensure the process is reaped on exit. This function returns true if the kill is successful, and false otherwise.
A Integer | undefined representing the process identifier (PID) of the child process. If the child process fails to spawn due to errors, then the value is undefined. When the child process exits, then the value is undefined after the exit event is emitted.
A NodeJS.ReadableStream | null that represents the child process’s stdout. If the child was spawned with options.stdio[1] set to anything other than ‘pipe’, then this will be null. When the child process exits, then the value is null after the exit event is emitted.
// Main process const { port1, port2 } = new MessageChannelMain() const child = utilityProcess.fork(path.join(__dirname, 'test.js')) child.stdout.on('data', (data) => { console.log(Received chunk ${data}) })
A NodeJS.ReadableStream | null that represents the child process’s stderr. If the child was spawned with options.stdio[2] set to anything other than ‘pipe’, then this will be null. When the child process exits, then the value is null after the exit event is emitted.
Tray icon uses StatusNotifierItem by default, when it is not available in user’s desktop environment the GtkStatusIcon will be used instead.
The click event is emitted when the tray icon receives activation from user, however the StatusNotifierItem spec does not specify which action would cause an activation, for some environments it is left mouse click, but for some it might be double left mouse click.
In order for changes made to individual MenuItems to take effect, you have to call setContextMenu again. For example:
// 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) })
MacOS
Icons passed to the Tray constructor should be Template Images.
To make sure your icon isn’t grainy on retina monitors, be sure your @2x image is 144dpi.
If you are bundling your application (e.g., with webpack for development), be sure that the file names are not being mangled or hashed. The filename needs to end in Template, and the @2x image needs to have the same filename as the standard image, or MacOS will not magically invert your image’s colors or use the high density image.
16×16 (72dpi) and 32×32@2x (144dpi) work well for most icons.
Windows
It is recommended to use ICO icons to get best visual effects.
guid string (optional) Windows – Assigns a GUID to the tray icon. If the executable is signed and the signature contains an organization in the subject line then 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 then 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. However, it is highly recommended to use the GUID parameter only in conjunction with code-signed executable. If an App defines multiple tray icons then each icon must use a separate GUID.
Creates a new tray icon associated with the image.
fontType string (optional) – The font family variant to display, can be monospaced or monospacedDigit. monospaced is available in macOS 10.15+ When left blank, the title uses the default system font.
Sets the title displayed next to the tray icon in the status bar (Support ANSI colors).
icon (NativeImage | string) (optional) – Icon to use when iconType is custom.
iconType string (optional) – Can be none, info, warning, error or custom. Default is custom.
title string
content string
largeIcon boolean (optional) – The large version of the icon should be used. Default is true. Maps to NIIF_LARGE_ICON.
noSound boolean (optional) – Do not play the associated sound. Default is false. Maps to NIIF_NOSOUND.
respectQuietTime boolean (optional) – Do not display the balloon notification if the current user is in “quiet time”. Default is false. Maps to NIIF_RESPECT_QUIET_TIME.
Returns focus to the taskbar notification area. Notification area icons should use this message when they have completed their UI operation. For example, if the icon displays a shortcut menu, but the user presses ESC to cancel it, use tray.focus() to return focus to the notification area.
A TouchBarItem that will replace the “esc” button on the touch bar when set. Setting to null restores the default “esc” button. Changing this value immediately updates the escape item in the touch bar.
deliverImmediately boolean (optional) – true to post notifications immediately even when the subscribing app is inactive.
Posts event as native notifications of macOS. The userInfo is an Object that contains the user information dictionary sent along with the notification.
Posts event as native notifications of macOS. The userInfo is an Object that contains the user information dictionary sent along with the notification.
Posts event as native notifications of macOS. The userInfo is an Object that contains the user information dictionary sent along with the notification.
Subscribes to native notifications of macOS, callback will be called with callback(event, userInfo) when the corresponding event happens. The userInfo is an Object that contains the user information dictionary sent along with the notification. The object is the sender of the notification, and only supports NSString values for now.
The id of the subscriber is returned, which can be used to unsubscribe the event.
Under the hood this API subscribes to NSDistributedNotificationCenter, example values of event are:
AppleInterfaceThemeChangedNotification
AppleAquaColorVariantChanged
AppleColorPreferencesChangedNotification
AppleShowScrollBarsSettingChanged
If event is null, the NSDistributedNotificationCenter doesn’t use it as criteria for delivery to the observer. See docs for more information.
Same as subscribeNotification, but uses NSNotificationCenter for local defaults. This is necessary for events such as NSUserDefaultsDidChangeNotification.
If event is null, the NSNotificationCenter doesn’t use it as criteria for delivery to the observer. See docs for more information.
Same as subscribeNotification, but uses NSWorkspace.sharedWorkspace.notificationCenter. This is necessary for events such as NSWorkspaceDidActivateApplicationNotification.
If event is null, the NSWorkspaceNotificationCenter doesn’t use it as criteria for delivery to the observer. See docs for more information.
Returns boolean – true if DWM composition (Aero Glass) is enabled, and false otherwise.
An example of using it to determine if you should create a transparent window or not (transparent windows won’t work correctly when DWM composition is disabled):
// Make the window transparent only if the platform supports it. if (process.platform !== 'win32' || systemPreferences.isAeroGlassEnabled()) { browserOptions.transparent = true browserOptions.frame = false }
// Create the window. const win = new BrowserWindow(browserOptions)
// Navigate. if (browserOptions.transparent) { win.loadFile('index.html') } else { // No transparency, so we load a fallback that uses basic styles. win.loadFile('fallback.html') }
3d-dark-shadow – Dark shadow for three-dimensional display elements.
3d-face – Face color for three-dimensional display elements and for dialog box backgrounds.
3d-highlight – Highlight color for three-dimensional display elements.
3d-light – Light color for three-dimensional display elements.
3d-shadow – Shadow color for three-dimensional display elements.
active-border – Active window border.
active-caption – Active window title bar. Specifies the left side color in the color gradient of an active window’s title bar if the gradient effect is enabled.
active-caption-gradient – Right side color in the color gradient of an active window’s title bar.
app-workspace – Background color of multiple document interface (MDI) applications.
button-text – Text on push buttons.
caption-text – Text in caption, size box, and scroll bar arrow box.
desktop – Desktop background color.
disabled-text – Grayed (disabled) text.
highlight – Item(s) selected in a control.
highlight-text – Text of item(s) selected in a control.
hotlight – Color for a hyperlink or hot-tracked item.
inactive-border – Inactive window border.
inactive-caption – Inactive window caption. Specifies the left side color in the color gradient of an inactive window’s title bar if the gradient effect is enabled.
inactive-caption-gradient – Right side color in the color gradient of an inactive window’s title bar.
inactive-caption-text – Color of text in an inactive caption.
info-background – Background color for tooltip controls.
info-text – Text color for tooltip controls.
menu – Menu background.
menu-highlight – The color used to highlight menu items when the menu appears as a flat menu.
menubar – The background color for the menu bar when menus appear as flat menus.
menu-text – Text in menus.
scrollbar – Scroll bar gray area.
window – Window background.
window-frame – Window frame.
window-text – Text in windows.
On macOS
control-background – The background of a large interface element, such as a browser or table.
control – The surface of a control.
control-text -The text of a control that isn’t disabled.
disabled-control-text – The text of a control that’s disabled.
find-highlight – The color of a find indicator.
grid – The gridlines of an interface element such as a table.
header-text – The text of a header cell in a table.
highlight – The virtual light source onscreen.
keyboard-focus-indicator – The ring that appears around the currently focused control when using the keyboard for interface navigation.
label – The text of a label containing primary content.
link – A link to other content.
placeholder-text – A placeholder string in a control or text view.
quaternary-label – The text of a label of lesser importance than a tertiary label such as watermark text.
scrubber-textured-background – The background of a scrubber in the Touch Bar.
secondary-label – The text of a label of lesser importance than a normal label such as a label used to represent a subheading or additional information.
selected-content-background – The background for selected content in a key window or view.
selected-control – The surface of a selected control.
selected-control-text – The text of a selected control.
selected-menu-item-text – The text of a selected menu.
selected-text-background – The background of selected text.
selected-text – Selected text.
separator – A separator between different sections of content.
shadow – The virtual shadow cast by a raised object onscreen.
tertiary-label – The text of a label of lesser importance than a secondary label such as a label used to represent disabled text.
text-background – Text background.
text – The text in a document.
under-page-background – The background behind a document’s content.
unemphasized-selected-content-background – The selected content in a non-key window or view.
unemphasized-selected-text-background – A background for selected text in a non-key window or view.
unemphasized-selected-text – Selected text in a non-key window or view.
window-background – The background of a window.
window-frame-text – The text in the window’s titlebar area.
Returns string – The system color setting in RGBA hexadecimal form (#RRGGBBAA). See the Windows docs and the macOS docs for more details.
The following colors are only available on macOS 10.14: find-highlight, selected-content-background, separator, unemphasized-selected-content-background, unemphasized-selected-text-background, and unemphasized-selected-text.
Returns string – The standard system color formatted as #RRGGBBAA.
Returns one of several standard system colors that automatically adapt to vibrancy and changes in accessibility settings like ‘Increase contrast’ and ‘Reduce transparency’. See Apple Documentation for more details.
reason string – The reason you are asking for Touch ID authentication
Returns Promise<void> – resolves if the user has successfully authenticated with Touch ID.
const { systemPreferences } = require('electron')
systemPreferences.promptTouchID('To get consent for a Security-Gated Thing').then(success => { console.log('You have successfully authenticated with Touch ID!') }).catch(err => { console.log(err) })
This API itself will not protect your user data; rather, it is a mechanism to allow you to do so. Native apps will need to set Access Control Constants like kSecAccessControlUserPresence on their keychain entry so that reading it would auto-prompt for Touch ID biometric consent. This could be done with node-keytar, such that one would store an encryption key with node-keytar and only fetch it if promptTouchID() resolves.
mediaType string – Can be microphone, camera or screen.
Returns string – Can be not-determined, granted, denied, restricted or unknown.
This user consent was not required on macOS 10.13 High Sierra so this method will always return granted. macOS 10.14 Mojave or higher requires consent for microphone and camera access. macOS 10.15 Catalina or higher requires consent for screen access.
Windows 10 has a global setting controlling microphone and camera access for all win32 applications. It will always return granted for screen and for all media types on older versions of Windows.
mediaType string – the type of media being requested; can be microphone, camera.
Returns Promise<boolean> – A promise that resolves with true if consent was granted and false if it was denied. If an invalid mediaType is passed, the promise will be rejected. If an access request was denied and later is changed through the System Preferences pane, a restart of the app will be required for the new permissions to take effect. If access has already been requested and denied, it must be changed through the preference pane; an alert will not pop up and the promise will resolve with the existing access status.
Important: In order to properly leverage this API, you must set the NSMicrophoneUsageDescription and NSCameraUsageDescription strings in your app’s Info.plist file. The values for these keys will be used to populate the permission dialogs so that the user will be properly informed as to the purpose of the permission request. See Electron Application Distribution for more information about how to set these in the context of Electron.
This user consent was not required until macOS 10.14 Mojave, so this method will always return true if your system is running 10.13 High Sierra.
shouldRenderRichAnimation boolean – Returns true if rich animations should be rendered. Looks at session type (e.g. remote desktop) and accessibility settings to give guidance for heavy animations.
scrollAnimationsEnabledBySystem boolean – Determines on a per-platform basis whether scroll animations (e.g. produced by home/end key) should be enabled.
prefersReducedMotion boolean – Determines whether the user desires reduced motion based on platform APIs.
activate boolean (optional) macOS – true to bring the opened application to the foreground. The default is true.
workingDirectory string (optional) Windows – The working directory.
logUsage boolean (optional) Windows – Indicates a user initiated launch that enables tracking of frequently used programs and other behaviors. The default is false.
Returns Promise<void>
Open the given external protocol URL in the desktop’s default manner. (For example, mailto: URLs in the user’s default mail agent).
The ShareMenu class creates Share Menu on macOS, which can be used to share information from the current context to apps, social media accounts, and other services.
For including the share menu as a submenu of other menus, please use the shareMenu role of MenuItem.
browserWindowBrowserWindow (optional) – Default is the focused window.
x number (optional) – Default is the current mouse cursor position. Must be declared if y is declared.
y number (optional) – Default is the current mouse cursor position. Must be declared if x is declared.
positioningItem number (optional) macOS – The index of the menu item to be positioned under the mouse cursor at the specified coordinates. Default is -1.
callback Function (optional) – Called when menu is closed.
Pops up this menu as a context menu in the BrowserWindow.