跳转至

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)

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.

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:

const { webContents } = require('electron')

console.log(webContents)

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)

  • id Integer

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)

  • frame WebFrameMain

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)

  • 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.

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:

  • event Event
  • errorCode Integer
  • errorDescription string
  • validatedURL string
  • isMainFrame boolean
  • frameProcessId Integer
  • frameRoutingId Integer

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:

  • event Event
  • errorCode Integer
  • errorDescription string
  • validatedURL string
  • isMainFrame boolean
  • frameProcessId Integer
  • frameRoutingId Integer

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:

  • event Event
  • isMainFrame boolean
  • frameProcessId Integer
  • frameRoutingId Integer

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:

  • event Event
  • title string
  • explicitSet boolean

Fired when page title is set during navigation. explicitSet is false when title is synthesized from file url.

Event: 'page-favicon-updated'

Returns:

  • event Event
  • favicons string[] - Array of URLs.

Emitted when page receives favicon urls.

Event: 'content-bounds-updated'

Returns:

  • event Event
  • bounds Rectangle - 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:

  • window BrowserWindow
  • details Object
  • url string - URL for the created window.
  • frameName string - Name given to the created window in the window.open() call.
  • options BrowserWindowConstructorOptions - 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.
  • referrer Referrer - 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.
  • postBody PostBody (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. 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:

  • details Event\<>
  • url string - The URL the frame is navigating to.
  • 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 | null - The frame to be navigated. May be null if accessed after the frame has either navigated or been destroyed.
  • initiator WebFrameMain | null (optional) - The frame which initiated the navigation. This can be a parent frame (e.g. via window.open with 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.
  • 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.

Event: 'will-frame-navigate'

Returns:

  • details Event\<>
  • url string - The URL the frame is navigating to.
  • 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 | null - The frame to be navigated. May be null if accessed after the frame has either navigated or been destroyed.
  • initiator WebFrameMain | null (optional) - The frame which initiated the navigation. This can be a parent frame (e.g. via window.open with 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:

  • details Event\<>
  • url string - The URL the frame is navigating to.
  • 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 | null - The frame to be navigated. May be null if accessed after the frame has either navigated or been destroyed.
  • initiator WebFrameMain | null (optional) - The frame which initiated the navigation. This can be a parent frame (e.g. via window.open with 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.
  • url string Deprecated
  • isInPlace boolean Deprecated
  • isMainFrame boolean Deprecated
  • frameProcessId Integer Deprecated
  • frameRoutingId Integer Deprecated

Emitted when any frame (including main) starts navigating.

Event: 'will-redirect'

Returns:

  • details Event\<>
  • url string - The URL the frame is navigating to.
  • 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 | null - The frame to be navigated. May be null if accessed after the frame has either navigated or been destroyed.
  • initiator WebFrameMain | null (optional) - The frame which initiated the navigation. This can be a parent frame (e.g. via window.open with 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.
  • 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).

Event: 'did-redirect-navigation'

Returns:

  • details Event\<>
  • url string - The URL the frame is navigating to.
  • 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 | null - The frame to be navigated. May be null if accessed after the frame has either navigated or been destroyed.
  • initiator WebFrameMain | null (optional) - The frame which initiated the navigation. This can be a parent frame (e.g. via window.open with 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.
  • 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 check out the will-redirect event above.

Event: 'did-navigate'

Returns:

  • event Event
  • url string
  • 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.

Event: 'did-frame-navigate'

Returns:

  • event Event
  • url string
  • 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.

Event: 'did-navigate-in-page'

Returns:

  • event Event
  • url string
  • isMainFrame boolean
  • frameProcessId Integer
  • frameRoutingId Integer

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:

  • event Event

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.

Event: 'render-process-gone'

Returns:

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:

Emitted when an input event is sent to the WebContents. See InputEvent for details.

Event: 'before-input-event'

Returns:

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:

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:

  • event Event
  • zoomDirection string - Can be in or out.

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:

  • event Event
  • url string - 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:

  • event Event
  • query string - 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:

  • event Event
  • url string
  • error string - The error code.
  • certificate Certificate
  • callback Function
  • isTrusted boolean - Indicates whether the certificate can be considered trusted.
  • isMainFrame boolean

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:

  • event Event
  • url URL
  • certificateList Certificate[]
  • callback Function
  • certificate Certificate - 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:

  • event Event
  • authenticationResponseDetails Object
  • url URL
  • pid number
  • isRequestForNavigation boolean - Indicates whether the request is for a navigation.
  • firstAuthAttempt boolean - Indicates whether this is the first authentication attempt.
  • responseHeaders Record\<string, string | string[]> (optional) - The headers returned in the response.
  • authInfo Object
  • isProxy boolean
  • scheme string
  • host string
  • port Integer
  • realm string
  • callback Function
  • username string (optional)
  • password string (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:

  • event Event
  • result Object
  • requestId Integer
  • activeMatchOrdinal Integer - Position of the active match.
  • matches Integer - Number of Matches.
  • selectionArea Rectangle - Coordinates of first match region.
  • finalUpdate boolean

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:

  • event Event\<>
  • audible boolean - True if one or more frames or child webContents are emitting audio.

Emitted when media becomes audible or inaudible.

Event: 'did-change-theme-color'

Returns:

  • event Event
  • color (string | null) - Theme color is in format of '#rrggbb'. It is null when no theme color is set.

Emitted when a page's theme color changes. This is usually due to encountering a meta tag:

<meta name='theme-color' content='#ff0000'>

Event: 'update-target-url'

Returns:

  • event Event
  • url string

Emitted when mouse moves over a link or the keyboard moves the focus to a link.

Event: 'cursor-changed'

Returns:

  • event Event
  • type string
  • image NativeImage (optional)
  • scale Float (optional) - scaling factor for the custom cursor.
  • size Size (optional) - the size of the image.
  • hotspot Point (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:

  • event Event
  • params Object
  • x Integer - x coordinate.
  • y Integer - y coordinate.
  • frame WebFrameMain | null - Frame from which the context menu was invoked. May be null if accessed after the frame has either navigated or been destroyed.
  • 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.
  • selectionRect Rectangle - Rect representing the coordinates in the document space of the selection.
  • selectionStartOffset number - Start position of the selection text.
  • referrerPolicy Referrer - 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.

Event: 'select-bluetooth-device'

Returns:

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.

main.js
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

  • offset Integer

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)

  • userAgent string

Overrides the user agent for this web page.

contents.getUserAgent()

Returns string - The user agent for this web page.

contents.insertCSS(css[, options])

  • css string
  • options Object (optional)
  • 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; }')
})

contents.removeInsertedCSS(key)

  • key string

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])

  • code string
  • 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
  })

contents.executeJavaScriptInIsolatedWorld(worldId, scripts[, userGesture])

  • 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.
  • scripts WebSource[]
  • 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.

Works like executeJavaScript but evaluates scripts in an isolated context.

contents.setIgnoreMenuShortcuts(ignore)

  • ignore boolean

Ignore application menu shortcuts while this web contents is focused.

contents.setWindowOpenHandler(handler)

  • handler Function\<WindowOpenHandlerResponse>
  • details Object
    • 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. 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.
    • referrer Referrer - 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.
    • postBody PostBody (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 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)

  • muted boolean

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)

  • factor Double - 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)

  • level number - 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' via contents.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)

  • minimumLevel number
  • maximumLevel number

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:

const win = new BrowserWindow()
win.webContents.setVisualZoomLevelLimits(1, 3)

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)

  • x Integer
  • y Integer

Copy the image at the given position to the clipboard.

contents.copyVideoFrameAt(x, y)

  • x Integer
  • y Integer

When executed on a video media element, copies the frame at (x, y) to the clipboard.

contents.saveVideoFrameAs(x, y)

  • x Integer
  • y Integer

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)

  • options Object
  • 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 })

Before:

Image Before Text Selection Adjustment

After:

Image After Text Selection Adjustment

contents.replace(text)

  • text string

Executes the editing command replace in web page.

contents.replaceMisspelling(text)

  • text string

Executes the editing command replaceMisspelling in web page.

contents.insertText(text)

  • text string

Returns Promise<void>

Inserts text to the focused element.

contents.findInPage(text[, options])

  • 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.

contents.stopFindInPage(action)

  • action string - Specifies the action to take place when ending webContents.findInPage request.
  • 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