webContents¶
Render and control web pages.
Process: Main
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:
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ width: 800, height: 1500 })
win.loadURL('https://github.com')
const contents = win.webContents
console.log(contents)
Navigation Events¶
Several events can be used to monitor navigations as they occur within a webContents.
Document Navigations¶
When a webContents navigates to another page (as opposed to an in-page navigation), the following events will be fired.
did-start-navigationwill-frame-navigatewill-navigate(only fired when main frame navigates)will-redirect(only fired when a redirect happens during navigation)did-redirect-navigation(only fired when a redirect happens during navigation)did-frame-navigatedid-navigate(only fired when main frame navigates)
Subsequent events will not fire if event.preventDefault() is called on any of the cancellable events.
In-page Navigation¶
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:
Frame Navigation¶
The will-navigate and did-navigate events only fire when the mainFrame navigates.
If you want to also observe navigations in <iframe>s, use will-frame-navigate and did-frame-navigate events.
Methods¶
These methods can be accessed from the webContents module:
webContents.getAllWebContents()¶
Returns WebContents[] - An array of all WebContents instances. This will contain web contents
for all windows, webviews, opened DevTools, and DevTools extension background pages.
webContents.getFocusedWebContents()¶
Returns WebContents | null - The web contents that is focused in this application, otherwise
returns null.
webContents.fromId(id)¶
idInteger
Returns WebContents | undefined - A WebContents instance with the given ID, or
undefined if there is no WebContents associated with the given ID.
webContents.fromFrame(frame)¶
frameWebFrameMain
Returns WebContents | undefined - A WebContents instance with the given WebFrameMain, or
undefined if there is no WebContents associated with the given WebFrameMain.
webContents.fromDevToolsTargetId(targetId)¶
targetIdstring - 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.
async function lookupTargetId (browserWindow) {
const wc = browserWindow.webContents
await wc.debugger.attach('1.3')
const { targetInfo } = await wc.debugger.sendCommand('Target.getTargetInfo')
const { targetId } = targetInfo
const targetWebContents = await wc.fromDevToolsTargetId(targetId)
}
Class: WebContents¶
Render and control the contents of a BrowserWindow instance.
Process: Main
This class is not exported from the 'electron' module. It is only available as a return value of other methods in the Electron API.
Instance Events¶
Event: 'did-finish-load'¶
Emitted when the navigation is done, i.e. the spinner of the tab has stopped
spinning, and the onload event was dispatched.
Event: 'did-fail-load'¶
Returns:
eventEventerrorCodeIntegererrorDescriptionstringvalidatedURLstringisMainFramebooleanframeProcessIdIntegerframeRoutingIdInteger
This event is like did-finish-load but emitted when the load failed.
The full list of error codes and their meaning is available here.
Event: 'did-fail-provisional-load'¶
Returns:
eventEventerrorCodeIntegererrorDescriptionstringvalidatedURLstringisMainFramebooleanframeProcessIdIntegerframeRoutingIdInteger
This event is like did-fail-load but emitted when the load was cancelled
(e.g. window.stop() was invoked).
Event: 'did-frame-finish-load'¶
Returns:
eventEventisMainFramebooleanframeProcessIdIntegerframeRoutingIdInteger
Emitted when a frame has done navigation.
Event: 'did-start-loading'¶
Corresponds to the points in time when the spinner of the tab started spinning.
Event: 'did-stop-loading'¶
Corresponds to the points in time when the spinner of the tab stopped spinning.
Event: 'dom-ready'¶
Emitted when the document in the top-level frame is loaded.
Event: 'page-title-updated'¶
Returns:
eventEventtitlestringexplicitSetboolean
Fired when page title is set during navigation. explicitSet is false when
title is synthesized from file url.
Event: 'page-favicon-updated'¶
Returns:
eventEventfaviconsstring[] - Array of URLs.
Emitted when page receives favicon urls.
Event: 'content-bounds-updated'¶
Returns:
eventEventboundsRectangle - requested new content bounds
Emitted when the page calls window.moveTo, window.resizeTo or related APIs.
By default, this will move the window. To prevent that behavior, call
event.preventDefault().
Event: 'did-create-window'¶
Returns:
windowBrowserWindowdetailsObjecturlstring - URL for the created window.frameNamestring - Name given to the created window in thewindow.open()call.optionsBrowserWindowConstructorOptions - The options used to create the BrowserWindow. They are merged in increasing precedence: parsed options from thefeaturesstring fromwindow.open(), security-related webPreferences inherited from the parent, and options given bywebContents.setWindowOpenHandler. Unrecognized options are not filtered out.referrerReferrer - The referrer that will be passed to the new window. May or may not result in theRefererheader 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 benull. Only defined when the window is being created by a form that settarget=_blank.dispositionstring - Can bedefault,foreground-tab,background-tab,new-windoworother. Corresponds to the manner an associated link was clicked. See Chromium's WindowOpenDisposition.default- Indicates Chromium deems in-window navigation valid for a window open call.foreground-tab- Corresponds to a left click or shift + middle click.background-tab- Corresponds to a middle click or ctrl/cmd + click.new-window- Corresponds to a shift + left click.other- A catch-all for the remaining Chromium dispositions not handled by Electron.
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.
Event: 'will-navigate'¶
Returns:
detailsEvent\<>urlstring - The URL the frame is navigating to.isSameDocumentboolean - This event does not fire for same document navigations using window.history api and reference fragment navigations. This property is always set tofalsefor this event.isMainFrameboolean - True if the navigation is taking place in a main frame.frameWebFrameMain | null - The frame to be navigated. May benullif accessed after the frame has either navigated or been destroyed.initiatorWebFrameMain | null (optional) - The frame which initiated the navigation. This can be a parent frame (e.g. viawindow.openwith a frame's name), a child frame (e.g. an unsandboxed iframe navigating its parent via<a target="_top">), 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.urlstring DeprecatedisInPlaceboolean DeprecatedisMainFrameboolean DeprecatedframeProcessIdInteger DeprecatedframeRoutingIdInteger 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.
Event: 'will-frame-navigate'¶
Returns:
detailsEvent\<>urlstring - The URL the frame is navigating to.isSameDocumentboolean - This event does not fire for same document navigations using window.history api and reference fragment navigations. This property is always set tofalsefor this event.isMainFrameboolean - True if the navigation is taking place in a main frame.frameWebFrameMain | null - The frame to be navigated. May benullif accessed after the frame has either navigated or been destroyed.initiatorWebFrameMain | null (optional) - The frame which initiated the navigation. This can be a parent frame (e.g. viawindow.openwith a frame's name), a child frame (e.g. an unsandboxed iframe navigating its parent via<a target="_top">), 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.
Event: 'did-start-navigation'¶
Returns:
detailsEvent\<>urlstring - The URL the frame is navigating to.isSameDocumentboolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation.isMainFrameboolean - True if the navigation is taking place in a main frame.frameWebFrameMain | null - The frame to be navigated. May benullif accessed after the frame has either navigated or been destroyed.initiatorWebFrameMain | null (optional) - The frame which initiated the navigation. This can be a parent frame (e.g. viawindow.openwith a frame's name), a child frame (e.g. an unsandboxed iframe navigating its parent via<a target="_top">), 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.urlstring DeprecatedisInPlaceboolean DeprecatedisMainFrameboolean DeprecatedframeProcessIdInteger DeprecatedframeRoutingIdInteger Deprecated
Emitted when any frame (including main) starts navigating.
Event: 'will-redirect'¶
Returns:
detailsEvent\<>urlstring - The URL the frame is navigating to.isSameDocumentboolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation.isMainFrameboolean - True if the navigation is taking place in a main frame.frameWebFrameMain | null - The frame to be navigated. May benullif accessed after the frame has either navigated or been destroyed.initiatorWebFrameMain | null (optional) - The frame which initiated the navigation. This can be a parent frame (e.g. viawindow.openwith a frame's name), a child frame (e.g. an unsandboxed iframe navigating its parent via<a target="_top">), 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.urlstring DeprecatedisInPlaceboolean DeprecatedisMainFrameboolean DeprecatedframeProcessIdInteger DeprecatedframeRoutingIdInteger 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).
Event: 'did-redirect-navigation'¶
Returns:
detailsEvent\<>urlstring - The URL the frame is navigating to.isSameDocumentboolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation.isMainFrameboolean - True if the navigation is taking place in a main frame.frameWebFrameMain | null - The frame to be navigated. May benullif accessed after the frame has either navigated or been destroyed.initiatorWebFrameMain | null (optional) - The frame which initiated the navigation. This can be a parent frame (e.g. viawindow.openwith a frame's name), a child frame (e.g. an unsandboxed iframe navigating its parent via<a target="_top">), 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.urlstring DeprecatedisInPlaceboolean DeprecatedisMainFrameboolean DeprecatedframeProcessIdInteger DeprecatedframeRoutingIdInteger 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
check out the will-redirect event above.
Event: 'did-navigate'¶
Returns:
eventEventurlstringhttpResponseCodeInteger - -1 for non HTTP navigationshttpStatusTextstring - 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.
Event: 'did-frame-navigate'¶
Returns:
eventEventurlstringhttpResponseCodeInteger - -1 for non HTTP navigationshttpStatusTextstring - empty for non HTTP navigations,isMainFramebooleanframeProcessIdIntegerframeRoutingIdInteger
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.
Event: 'did-navigate-in-page'¶
Returns:
eventEventurlstringisMainFramebooleanframeProcessIdIntegerframeRoutingIdInteger
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.
Event: 'will-prevent-unload'¶
Returns:
eventEvent
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
BrowserViewsbut will not be respected - this is because we have chosen not to tie theBrowserViewlifecycle to its owning BrowserWindow should one exist per the specification.
Event: 'render-process-gone'¶
Returns:
eventEventdetailsRenderProcessGoneDetails
Emitted when the renderer process unexpectedly disappears. This is normally because it was crashed or killed.
Event: 'unresponsive'¶
Emitted when the web page becomes unresponsive.
Event: 'responsive'¶
Emitted when the unresponsive web page becomes responsive again.
Event: 'destroyed'¶
Emitted when webContents is destroyed.
Event: 'input-event'¶
Returns:
eventEventinputEventInputEvent
Emitted when an input event is sent to the WebContents. See InputEvent for details.
Event: 'before-input-event'¶
Returns:
eventEventinputObject - Input properties.typestring - EitherkeyUporkeyDown.keystring - Equivalent to KeyboardEvent.key.codestring - Equivalent to KeyboardEvent.code.isAutoRepeatboolean - Equivalent to KeyboardEvent.repeat.isComposingboolean - Equivalent to KeyboardEvent.isComposing.shiftboolean - Equivalent to KeyboardEvent.shiftKey.controlboolean - Equivalent to KeyboardEvent.controlKey.altboolean - Equivalent to KeyboardEvent.altKey.metaboolean - Equivalent to KeyboardEvent.metaKey.locationnumber - Equivalent to KeyboardEvent.location.modifiersstring[] - See InputEvent.modifiers.
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.
To only prevent the menu shortcuts, use
setIgnoreMenuShortcuts:
const { app, BrowserWindow } = require('electron')
app.whenReady().then(() => {
const win = new BrowserWindow({ width: 800, height: 600 })
win.webContents.on('before-input-event', (event, input) => {
// Enable application menu keyboard shortcuts when Ctrl/Cmd are down.
win.webContents.setIgnoreMenuShortcuts(!input.control && !input.meta)
})
})
Event: 'before-mouse-event'¶
Returns:
eventEventmouseMouseInputEvent
Emitted before dispatching mouse events in the page.
Calling event.preventDefault will prevent the page mouse events.
const { app, BrowserWindow } = require('electron')
app.whenReady().then(() => {
const win = new BrowserWindow({ width: 800, height: 600 })
win.webContents.on('before-mouse-event', (event, mouse) => {
// Prevent mouseDown events.
if (mouse.type === 'mouseDown') {
console.log(mouse)
/*
{
type: 'mouseDown',
clickCount: 1,
movementX: 0,
movementY: 0,
button: 'left',
x: 632.359375,
y: 480.6875,
globalX: 168.359375,
globalY: 193.6875
}
*/
event.preventDefault()
}
})
})
Event: 'enter-html-full-screen'¶
Emitted when the window enters a full-screen state triggered by HTML API.
Event: 'leave-html-full-screen'¶
Emitted when the window leaves a full-screen state triggered by HTML API.
Event: 'zoom-changed'¶
Returns:
eventEventzoomDirectionstring - Can beinorout.
Emitted when the user is requesting to change the zoom level using the mouse wheel.
Event: 'blur'¶
Emitted when the WebContents loses focus.
Event: 'focus'¶
Emitted when the WebContents gains focus.
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.
Event: 'devtools-open-url'¶
Returns:
eventEventurlstring - URL of the link that was clicked or selected.
Emitted when a link is clicked in DevTools or 'Open in new tab' is selected for a link in its context menu.
Event: 'devtools-search-query'¶
Returns:
eventEventquerystring - text to query for.
Emitted when 'Search' is selected for text in its context menu.
Event: 'devtools-opened'¶
Emitted when DevTools is opened.
Event: 'devtools-closed'¶
Emitted when DevTools is closed.
Event: 'devtools-focused'¶
Emitted when DevTools is focused / opened.
Event: 'certificate-error'¶
Returns:
eventEventurlstringerrorstring - The error code.certificateCertificatecallbackFunctionisTrustedboolean - Indicates whether the certificate can be considered trusted.isMainFrameboolean
Emitted when failed to verify the certificate for url.
The usage is the same with the certificate-error event of app.
Event: 'select-client-certificate'¶
Returns:
eventEventurlURLcertificateListCertificate[]callbackFunctioncertificateCertificate - Must be a certificate from the given list.
Emitted when a client certificate is requested.
The usage is the same with the select-client-certificate event of app.
Event: 'login'¶
Returns:
eventEventauthenticationResponseDetailsObjecturlURLpidnumberisRequestForNavigationboolean - Indicates whether the request is for a navigation.firstAuthAttemptboolean - Indicates whether this is the first authentication attempt.responseHeadersRecord\<string, string | string[]> (optional) - The headers returned in the response.authInfoObjectisProxybooleanschemestringhoststringportIntegerrealmstringcallbackFunctionusernamestring (optional)passwordstring (optional)
Emitted when webContents wants to do basic auth.
The usage is the same with the login event of app.
Event: 'found-in-page'¶
Returns:
eventEventresultObjectrequestIdIntegeractiveMatchOrdinalInteger - Position of the active match.matchesInteger - Number of Matches.selectionAreaRectangle - Coordinates of first match region.finalUpdateboolean
Emitted when a result is available for
webContents.findInPage request.
Event: 'media-started-playing'¶
Emitted when media starts playing.
Event: 'media-paused'¶
Emitted when media is paused or done playing.
Event: 'audio-state-changed'¶
Returns:
eventEvent\<>audibleboolean - True if one or more frames or childwebContentsare emitting audio.
Emitted when media becomes audible or inaudible.
Event: 'did-change-theme-color'¶
Returns:
eventEventcolor(string | null) - Theme color is in format of '#rrggbb'. It isnullwhen no theme color is set.
Emitted when a page's theme color changes. This is usually due to encountering a meta tag:
Event: 'update-target-url'¶
Returns:
eventEventurlstring
Emitted when mouse moves over a link or the keyboard moves the focus to a link.
Event: 'cursor-changed'¶
Returns:
eventEventtypestringimageNativeImage (optional)scaleFloat (optional) - scaling factor for the custom cursor.sizeSize (optional) - the size of theimage.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.
Event: 'context-menu'¶
Returns:
eventEventparamsObjectxInteger - x coordinate.yInteger - y coordinate.frameWebFrameMain | null - Frame from which the context menu was invoked. May benullif accessed after the frame has either navigated or been destroyed.linkURLstring - URL of the link that encloses the node the context menu was invoked on.linkTextstring - Text associated with the link. May be an empty string if the contents of the link are an image.pageURLstring - URL of the top level page that the context menu was invoked on.frameURLstring - URL of the subframe that the context menu was invoked on.srcURLstring - Source URL for the element that the context menu was invoked on. Elements with source URLs are images, audio and video.mediaTypestring - Type of the node the context menu was invoked on. Can benone,image,audio,video,canvas,fileorplugin.hasImageContentsboolean - Whether the context menu was invoked on an image which has non-empty contents.isEditableboolean - Whether the context is editable.selectionTextstring - Text of the selection that the context menu was invoked on.titleTextstring - Title text of the selection that the context menu was invoked on.altTextstring - Alt text of the selection that the context menu was invoked on.suggestedFilenamestring - 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.selectionStartOffsetnumber - Start position of the selection text.referrerPolicyReferrer - The referrer policy of the frame on which the menu is invoked.misspelledWordstring - The misspelled word under the cursor, if any.dictionarySuggestionsstring[] - An array of suggested words to show the user to replace themisspelledWord. Only available if there is a misspelled word and spellchecker is enabled.frameCharsetstring - The character encoding of the frame on which the menu was invoked.formControlTypestring - The source that the context menu was invoked on. Possible values includenone,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, andtext-area,spellcheckEnabledboolean - If the context is editable, whether or not spellchecking is enabled.menuSourceTypestring - Input source that invoked the context menu. Can benone,mouse,keyboard,touch,touchMenu,longPress,longTap,touchHandle,stylus,adjustSelection, oradjustSelectionReset.mediaFlagsObject - The flags for the media element the context menu was invoked on.inErrorboolean - Whether the media element has crashed.isPausedboolean - Whether the media element is paused.isMutedboolean - Whether the media element is muted.hasAudioboolean - Whether the media element has audio.isLoopingboolean - Whether the media element is looping.isControlsVisibleboolean - Whether the media element's controls are visible.canToggleControlsboolean - Whether the media element's controls are toggleable.canPrintboolean - Whether the media element can be printed.canSaveboolean - Whether or not the media element can be downloaded.canShowPictureInPictureboolean - Whether the media element can show picture-in-picture.isShowingPictureInPictureboolean - Whether the media element is currently showing picture-in-picture.canRotateboolean - Whether the media element can be rotated.canLoopboolean - Whether the media element can be looped.
editFlagsObject - These flags indicate whether the renderer believes it is able to perform the corresponding action.canUndoboolean - Whether the renderer believes it can undo.canRedoboolean - Whether the renderer believes it can redo.canCutboolean - Whether the renderer believes it can cut.canCopyboolean - Whether the renderer believes it can copy.canPasteboolean - Whether the renderer believes it can paste.canDeleteboolean - Whether the renderer believes it can delete.canSelectAllboolean - Whether the renderer believes it can select all.canEditRichlyboolean - Whether the renderer believes it can edit text richly.
Emitted when there is a new context menu that needs to be handled.
Event: 'select-bluetooth-device'¶
Returns:
eventEventdevicesBluetoothDevice[]callbackFunctiondeviceIdstring
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 no event listener is added for this event, all bluetooth requests will be cancelled.
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.
const { app, BrowserWindow } = require('electron')
let win = null
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)
}
})
})
Event: 'paint'¶
Returns boolean - Whether the browser can go forward to next web page.
Deprecated: Should use the new contents.navigationHistory.canGoForward API.
contents.canGoToOffset(offset) Deprecated¶
Clears the navigation history.
Deprecated: Should use the new contents.navigationHistory.clear API.
contents.goBack() Deprecated¶
Makes the browser go forward a web page.
Deprecated: Should use the new contents.navigationHistory.goForward API.
contents.goToIndex(index) Deprecated¶
offsetInteger
Navigates to the specified offset from the "current entry".
Deprecated: Should use the new contents.navigationHistory.goToOffset API.
contents.isCrashed()¶
Returns boolean - Whether the renderer process has crashed.
contents.forcefullyCrashRenderer()¶
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()
}
})
contents.setUserAgent(userAgent)¶
userAgentstring
Overrides the user agent for this web page.
contents.getUserAgent()¶
Returns string - The user agent for this web page.
contents.insertCSS(css[, options])¶
cssstringoptionsObject (optional)cssOriginstring (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; }')
})
contents.removeInsertedCSS(key)¶
keystring
Returns Promise<void> - Resolves if the removal was successful.
Removes the inserted CSS from the current web page. The stylesheet is identified
by its key, which is returned from contents.insertCSS(css).
const win = new BrowserWindow()
win.webContents.on('did-finish-load', async () => {
const key = await win.webContents.insertCSS('html, body { background-color: #f00; }')
win.webContents.removeInsertedCSS(key)
})
contents.executeJavaScript(code[, userGesture])¶
codestringuserGestureboolean (optional) - Default isfalse.
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
})
contents.executeJavaScriptInIsolatedWorld(worldId, scripts[, userGesture])¶
worldIdInteger - The ID of the world to run the javascript in,0is the default world,999is the world used by Electron'scontextIsolationfeature. You can provide any integer here.scriptsWebSource[]userGestureboolean (optional) - Default isfalse.
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.
Works like executeJavaScript but evaluates scripts in an isolated context.
contents.setIgnoreMenuShortcuts(ignore)¶
ignoreboolean
Ignore application menu shortcuts while this web contents is focused.
contents.setWindowOpenHandler(handler)¶
handlerFunction\<WindowOpenHandlerResponse>detailsObjecturlstring - The resolved version of the URL passed towindow.open(). e.g. opening a window withwindow.open('foo')will yield something likehttps://the-origin/the/current/path/foo.frameNamestring - Name of the window provided inwindow.open()featuresstring - Comma separated list of window features provided towindow.open().dispositionstring - Can bedefault,foreground-tab,background-tab,new-windoworother. Corresponds to the manner an associated link was clicked. See Chromium's WindowOpenDisposition.default- Indicates Chromium deems in-window navigation valid for a window open call.foreground-tab- Corresponds to a left click or shift + middle click.background-tab- Corresponds to a middle click or ctrl/cmd + click.new-window- Corresponds to a shift + left click.other- A catch-all for the remaining Chromium dispositions not handled by Electron.referrerReferrer - The referrer that will be passed to the new window. May or may not result in theRefererheader 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 benull. Only defined when the window is being created by a form that settarget=_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 when 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:
const { BrowserView, BrowserWindow } = require('electron')
const mainWindow = new BrowserWindow()
mainWindow.webContents.setWindowOpenHandler((details) => {
return {
action: 'allow',
createWindow: (options) => {
const browserView = new BrowserView(options)
mainWindow.addBrowserView(browserView)
browserView.setBounds({ x: 0, y: 0, width: 640, height: 480 })
// For `background-tab` disposition (e.g., when middle-clicking or ctrl/cmd-clicking a link),
// `options.webContents` is undefined because its creation can be deferred. So load the URL manually.
if (details.disposition === 'background-tab') {
browserView.webContents.loadURL(details.url)
}
return browserView.webContents
}
}
})
contents.setAudioMuted(muted)¶
mutedboolean
Mute the audio on the current web page.
contents.isAudioMuted()¶
Returns boolean - Whether this page has been muted.
contents.isCurrentlyAudible()¶
Returns boolean - Whether audio is currently playing.
contents.setCaretBrowsingEnabled(enabled)¶
Returns boolean - Whether caret browsing is enabled for this page.
contents.setZoomFactor(factor)¶
factorDouble - Zoom factor; default is 1.0.
Changes the zoom factor to the specified factor. Zoom factor is zoom percent divided by 100, so 300% = 3.0.
The factor must be greater than 0.0.
contents.getZoomFactor()¶
Returns number - the current zoom factor.
contents.setZoomLevel(level)¶
levelnumber - Zoom level.
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 by default, meaning that the zoom level for a specific domain propagates across all instances of windows with the same domain. To use per-webContents zoom instead, set the zoom mode to
'isolated'viacontents.setZoomMode('isolated').
contents.getZoomLevel()¶
Returns number - the current zoom level.
contents.setZoomMode(mode)¶
Returns string - The current zoom mode. Can be default, isolated,
manual, or disabled.
contents.setVisualZoomLevelLimits(minimumLevel, maximumLevel)¶
minimumLevelnumbermaximumLevelnumber
Returns Promise<void>
Sets the maximum and minimum pinch-to-zoom level.
[!NOTE] Visual zoom is disabled by default in Electron. To re-enable it, call:
contents.undo()¶
Executes the editing command undo in web page.
contents.redo()¶
Executes the editing command redo in web page.
contents.cut()¶
Executes the editing command cut in web page.
contents.copy()¶
Executes the editing command copy in web page.
contents.centerSelection()¶
Centers the current text selection in web page.
contents.copyImageAt(x, y)¶
xIntegeryInteger
Copy the image at the given position to the clipboard.
contents.copyVideoFrameAt(x, y)¶
xIntegeryInteger
When executed on a video media element, copies the frame at (x, y) to the clipboard.
contents.saveVideoFrameAs(x, y)¶
xIntegeryInteger
When executed on a video media element, shows a save dialog and saves the frame at (x, y) to disk.
contents.paste()¶
Executes the editing command paste in web page.
contents.pasteAndMatchStyle()¶
Executes the editing command pasteAndMatchStyle in web page.
contents.delete()¶
Executes the editing command delete in web page.
contents.selectAll()¶
Executes the editing command selectAll in web page.
contents.unselect()¶
Executes the editing command unselect in web page.
contents.scrollToTop()¶
Scrolls to the top of the current webContents.
contents.scrollToBottom()¶
Scrolls to the bottom of the current webContents.
contents.adjustSelection(options)¶
optionsObjectstartNumber (optional) - Amount to shift the start index of the current selection.endNumber (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 })
Before:

After:

contents.replace(text)¶
textstring
Executes the editing command replace in web page.
contents.replaceMisspelling(text)¶
textstring
Executes the editing command replaceMisspelling in web page.
contents.insertText(text)¶
textstring
Returns Promise<void>
Inserts text to the focused element.
contents.findInPage(text[, options])¶
textstring - Content to be searched, must not be empty.optionsObject (optional)forwardboolean (optional) - Whether to search forward or backward, defaults totrue.findNextboolean (optional) - Whether to begin a new text finding session with this request. Should betruefor initial requests, andfalsefor follow-up requests. Defaults tofalse.matchCaseboolean (optional) - Whether search should be case-sensitive, defaults tofalse.
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.
contents.stopFindInPage(action)¶
actionstring - Specifies the action to take place when endingwebContents.findInPagerequest.clearSelection- Clear the selection.keepSelection- Translate the selection into a normal selection.activateSelection- Focus and click the selection node.
Stops any findInPage request for the webContents with the provided action.
const win = new BrowserWindow()
win.webContents.on('found-in-page', (event, result) => {
if (result.finalUpdate) win.webContents.stopFindInPage('clearSelection')
})
const requestId = win.webContents.findInPage('api')
console.log(requestId)
contents.capturePage([rect, opts])¶
A boolean property that determines whether caret browsing is enabled for this page.
When enabled, a movable cursor is placed in the page's text, allowing the user to navigate and select content with the keyboard. Changes apply to the live page without reloading it.
A <webview> guest inherits this value from its embedder when it is created and
then tracks it independently, so disabling caret browsing on the embedder leaves
an existing guest enabled.
While any WebContents in the process has caret browsing enabled, assistive
technology is notified process-wide that caret browsing is active, so that screen
readers report the caret's position as it moves. That notification is only
withdrawn once every WebContents that enabled caret browsing has either
disabled it or been destroyed.
contents.userAgent¶
A string property that determines the user agent for this web page.
contents.zoomLevel¶
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.
contents.zoomFactor¶
A number property that determines the zoom factor for this web contents.
The zoom factor is the zoom percent divided by 100, so 300% = 3.0.
contents.zoomMode¶
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.
contents.mainFrame Readonly¶
A WebFrameMain property that represents the top frame of the page's frame hierarchy.
contents.opener Readonly¶
A WebFrameMain | null property that represents the frame that opened this WebContents, either
with open(), or by navigating a link with a target attribute.
contents.focusedFrame Readonly¶
A WebFrameMain | null property that represents the currently focused frame in this WebContents.
Can be the top frame, an inner <iframe>, or null if nothing is focused.
本页原文 Markdown:在 AtomGit 查看·内容源自开源项目 el/electron