Saltar al contenido principal

webContents

Procesamiento y control de páginas webs.

Proceso: principal</0>

webContents es un EventEmitter. Es responsable de renderizar y controlar una página web y es una propiedad del objeto BrowserWindow. Un ejemplo de acceso al objeto webContents:

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.

Métodos

Se pueden acceder a estos métodos desde el módulo webContents:

const { webContents } = require('electron')
console.log(webContents)

webContents.getAllWebContents()

Volver WebContents[] a la matriz de todo el caso WebContents. Esto incluirá contenido web para todos los windows, páginas web, devtools abiertos y extensión de páginas de origen devtools.

webContents.getFocusedWebContents()

Returns WebContents | null - The web contents that is focused in this application, otherwise returns null.

webContents.fromId(id)

  • id Íntegro

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

Clase: WebContents

Renderice y controle el contenido de una instancia de BrowserWindow.

Proceso: Main
Esta clase no está exportada desde el módulo 'electron'. Sólo está disponible como un valor de retorno de otros métodos en la API de Electron.

Eventos de Instancia

Evento: 'did-finish-load'

Emite cuando la navegación está hecha, i.e.

Evento: 'did-fail-load'

Devuelve:

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

Este evento es como did-finish-load pero emitido cuando falló la carga. The full list of error codes and their meaning is available here.

Evento: 'did-fail-provisional-load'

Devuelve:

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

Este evento es como did-fail-load pero emitido cuando la carga fue cancelada (p. e. fue invocado window.stop()).

Evento: 'did-frame-finish-load'

Devuelve:

  • event
  • isMainFrame boolean
  • frameProcessId Integer
  • frameRoutingId Entero

Emite cuando un frame ha terminado la navegación.

Evento: 'did-start-loading'

Corresponde a los puntos en el tiempo cuando el girador de la pestaña comenzó a girar.

Evento: 'did-stop-loading'

Corresponde a los puntos en tiempo cuando el girador del tabulador terminó de girar.

Evento: 'dom-ready'

Emitido cuando el documento el el nivel superior está cargado.

Evento: 'page-title-updated'

Devuelve:

  • event
  • title string
  • explicitSet boolen

Disparado cuando el título de la página se configura durante la navegación. explicitSet es false cuando el título es sincronizado desde el archivo url.

Evento: 'page-favicon-updated'

Devuelve:

  • event
  • favicons string[] - matriz de URLs.

Emite cuando la página recibe urls de favicon.

Event: 'content-bounds-updated'

Devuelve:

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

Evento: 'did-create-window'

Devuelve:

  • window Navegador Windows
  • 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. Las opciones no reconocidas no están filtradas.
    • referrer Referrer - The referrer that will be passed to the new window. Puede resultar o no en la cabecera Referer siendo enviado, dependiendo de la política de referencia.
    • postBody PostBody (optional) - The post data that will be sent to the new window, along with the appropriate headers that will be set. Si no hay datos para enviar, el valor será 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.

Evento: 'will-navigate'

Devuelve:

  • 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 - 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. Puede ocurrir cuando el objeto window.location se cambia o un usuario hace clic en un enlace en la página.

Este evento no se emitirá cuando la navegación es iniciada con programación con APIs como webContents.loadURL y 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.

Llamando event.preventDefault() evitará la navegación.

Event: 'will-frame-navigate'

Devuelve:

  • 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 - 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. Puede ocurrir cuando el objeto window.location se cambia o un usuario hace clic en un enlace en la página.

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.

Este evento no se emitirá cuando la navegación es iniciada con programación con APIs como webContents.loadURL y 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.

Llamando event.preventDefault() evitará la navegación.

Evento: 'did-start-navigation'

Devuelve:

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

Emitido cuando cualquier frame (incluyendo el principal) comienza la navegación.

Evento: 'will-redirect'

Devuelve:

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

Este evento sera emitido después de did-start-navigation y siempre antes del evento did-redirect-navigation para la misma navegación.

Llamar a event.preventDefault() evitará la navegación (no solo la redirección).

Evento: 'did-redirect-navigation'

Devuelve:

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

Este evento no puede ser prevenir. Si quieres prevenir redirecciones deber ver el evento will-redirect arriba.

Evento: 'did-navigate'

Devuelve:

  • event
  • url string
  • httpResponseCode Integer - -1 para navegaciones no HTTP
  • httpStatusText string - empty for non HTTP navigations

Emitido cuando se realizo un navegación del frame principal.

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.

Evento: 'did-frame-navigate'

Devuelve:

  • event
  • url string
  • httpResponseCode Integer - -1 para navegaciones no HTTP
  • httpStatusText string - empty for non HTTP navigations,
  • isMainFrame boolean
  • frameProcessId Integer
  • frameRoutingId Entero

Emitido cuando se ha realizado un navegación de algun frame.

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.

Evento: 'did-navigate-in-page'

Devuelve:

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

Emitido cuando se produjo una navegación en la página en cualquier frame.

Cuando una navegación dentro de la página sucede, el URL de la página cambia, pero no causa una navegación fuera de la página. Ejemplos de ésto ocurriendo son cuando los links son clickeados o cuando el evento DOM hashchange es activado.

Evento: 'will-prevent-unload'

Devuelve:

  • event

Emite cuando un controlador de eventos beforeunload está tratando de cancelar una descarga de la página.

Llamando a event.preventDefault() ignorará el controlador de eventos beforeunload y permite que la página sea descargada.

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.

Evento: 'render-process-gone'

Devuelve:

Emitido cuando el renderer process desaparece inesperadamente. Esto se debe comúnmente porque se crasheo o cerro.

Evento: "unresponsive"

Aparece cuando la página web deja de responder.

Evento: "responsive"

Aparece cuando la página web que no responde vuelve a responder.

Evento: 'plugin-crashed'

Devuelve:

  • event
  • name string
  • version cadena

Emitido cuando el proceso de enchufe se ha caído.

Evento: 'destroyed'

Emitido cuando webContents es destruido.

Event: 'input-event'

Devuelve:

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

Evento: 'before-input-event'

Devuelve:

Emitido antes de enviar los eventos keydown y keyup en la página. Llamando a event.preventDefault evitará la página keydown/ eventos keyup y los accesos rápidos al menú.

To only prevent the menu shortcuts, use setIgnoreMenuShortcuts:

const { BrowserWindow } = require('electron')

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

Evento: "enter-html-full-screen"

Aparece cuando la ventana entra en un estado pantalla completa activado por la API HTML.

Evento: "leave-html-full-screen"

Aparece cuando la ventana sale de un estado pantalla completa activado por la API HTML.

Evento: 'zoom-changed'

Devuelve:

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

Emitido cuando es usuario esta solicitando cambiar el nivel del zoom usando la rueda del ratón.

Evento: "blur"

Emitted when the WebContents loses focus.

Evento: "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'

Devuelve:

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

Devuelve:

  • event
  • query string - text to query for.

Emitted when 'Search' is selected for text in its context menu.

Evento: 'devtools-opened'

Emitido cuando DevTools es abierto.

Evento: 'devtools-closed'

Emitido cuando Devtools es cerrado.

Evento: 'devtools-focused'

Emitido cuando DevTools es centrado o abierto.

Evento: 'error-certificado'

Devuelve:

  • event
  • url string
  • error cadena - el error del código.
  • certificate Certificate
  • callback Function
    • isTrusted boolean - indica si el certificado se puede considerar de confianza.
  • isMainFrame boolean

Emitido cuando no se pudo verificar el certificate for url.

The usage is the same with the certificate-error event of app.

Evento: 'select--client-certificate'

Devuelve:

  • event
  • url URL
  • certificateList Certificate[]
  • callback Function
    • certificate Certificate - Must be a certificate from the given list.

Emitido cuando el certificado de un cliente es requerido.

El uso es el mismo con the select-client-certificate evento de app.

Evento:'login'

Devuelve:

  • event
  • authenticationResponseDetails Object
    • url URL
  • authInfo Object
    • isProxy boolean
    • scheme string
    • host string
    • puerto Íntegro
    • realm string
  • callback Function
    • username string (optional)
    • password string (optional)

Emitido cuando webContents quiere hacer una autenticación básica.

El uso es lo mismo que con el evento the login de la app.

Evento: 'found-in-page'

Devuelve:

  • event
  • Objeto result
    • requestId Íntegro
    • activeMatchOrdinal Íntegro - Posición de un partido activo.
    • matches Íntegro - Número de Coincidencias.
    • selectionArea Rectangle - Coordenadas de la primera región de coincidencia.
    • finalUpdate boolean

Emitted when a result is available for webContents.findInPage request.

Evento: 'media-started-playing'

Emitido cuando la media empieza a reproducirse.

Evento: 'media-paused'

Emitido cuando la media es pausada o ha terminado de reproducirse.

Event: 'audio-state-changed'

Devuelve:

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

Emitted when media becomes audible or inaudible.

Evento: 'did-change-theme-color'

Devuelve:

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

Evento: 'update-target-url'

Devuelve:

  • event
  • url string

Emitido cuando el mouse se mueve sobre un link o el teclado se mueve el concentrado a un link.

Evento: 'cursor-changed'

Devuelve:

  • event
  • type string
  • image NativeImage (opcional)
  • scale Float (opcional) - Factor de escala para el cursor personalizado.
  • size Size (opcional) - El tamaño de la image.
  • hotspot Point (opcional) - Coordenadas de la zona activa del cursor personalizado.

Emitido cuando el tipo del cursor cambia. 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.

Evento: 'context-menu'

Devuelve:

  • event
  • params Object
    • x Integer - x coordinate.
    • y Integer - y coordinate.
    • frame WebFrameMain - Frame desde el cual se invocó el menú contextual.
    • 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. Puede ser none, image, audio, video, canvas, file o 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. Solo disponible si hay una palabra mal escrita y el corrector está habilitado.
    • 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. Puede ser none, mouse, keyboard, touch, touchMenu, longPress, longTap, touchHandle, stylus, adjustSelection, o 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.

Emitido cuando hay un nuevo menú de contexto que debe ser manejado.

Evento: 'select-bluetooth-device'

Devuelve:

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.

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

Evento: 'paint'

Devuelve:

Emitted when a new frame is generated. Only the dirty area is passed in the buffer.

const { BrowserWindow } = require('electron')

const win = new BrowserWindow({ webPreferences: { offscreen: true } })
win.webContents.on('paint', (event, dirty, image) => {
// updateBitmap(dirty, image.getBitmap())
})
win.loadURL('https://github.com')

Evento: 'devtools-reload-page'

Emitido cuando la ventana devtools instruya la webContents para recargar

Evento: 'will-attach-webview'

Devuelve:

  • event
  • webPreferences WebPreferences - 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.

Este evento puede utilizarse para configurar webPreferences para la webContents de un <webview>antes de que se carga y proporciona la capacidad de configuración que no se puede establecer a través de atributos <webview>.

Event: 'did-attach-webview'

Devuelve:

  • event
  • webContents WebContents - El contenido de la página web invitada que será usado por <webview>.

Emitido cuando se ha adjuntado un <webview> a este contenido web.

Evento: 'console-message'

Devuelve:

  • event
  • level Entero - El nivel de registro, desde 0 hasta 3. In order it matches verbose, info, warning and error.
  • message string - The actual console message
  • line Entero - El número de línea de la fuente que activó este mensaje de consola
  • sourceId cadena

Emitido cuando la ventana asociada registra un mensaje de consola.

Evento: 'error-preload'

Devuelve:

  • event
  • preloadPath string
  • error Error

Emitido cuando el script de preload preloadPathlanza una excepción no manejada error.

Evento: 'ipc-message'

Devuelve:

Emitido cuando el proceso de renderizado enviá un mensaje asíncrono a través de ipcRenderer.send().

See also webContents.ipc, which provides an IpcMain-like interface for responding to IPC messages specifically from this WebContents.

Evento: 'ipc-message-sync'

Devuelve:

Emitido cuando el proceso de renderizado envía un mensaje sincronídico a través de ipcRenderer.sendSync().

See also webContents.ipc, which provides an IpcMain-like interface for responding to IPC messages specifically from this WebContents.

Evento: 'preferred-size-changed'

Devuelve:

  • event
  • preferredSize Size - The minimum size needed to contain the layout of the document—without requiring scrolling.

Emitted when the WebContents preferred size has changed.

This event will only be emitted when enablePreferredSizeMode is set to true in webPreferences.

Evento: 'frame-created'

Devuelve:

  • event
  • details Object
    • frame WebFrameMain

Emitted when the mainFrame, an <iframe>, or a nested <iframe> is loaded within the page.

Métodos de Instancia

contents.loadURL(url[, options])

  • url string
  • options Object (opcional)
    • httpReferrer (string | Referrer) (opcional) - Una url HTTP de referencia.
    • userAgent string (opcional) - Un agente de usuario originando el pedido.
    • extraHeaders string (optional) - Extra headers separated by "\n".
    • postData (UploadRawData | UploadFile)[] (optional)
    • baseURLForDataURL string (opcional) - Url base (con separadores de ruta arrastrables) para archivos que se cargan por el url de datos. Esto es necesario únicamente si el url especificado es un url de datos y necesita cargar otros archivos.

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). Un manejador de rechazo noop ya esta adjunto, el cual evita errores de rechazo no controlados.

Carga el url en la ventana. El url debe contener el prefijo de protocolo. Por ejemplo http:// o file://. Si la carga debe omitir el caché http entonces hay que utilizar el encabezado pragma para lograrlo.

const win = new BrowserWindow()
const options = { extraHeaders: 'pragma: no-cache\n' }
win.webContents.loadURL('https://github.com', options)

contents.loadFile(filePath[, options])

  • filePath string
  • options Object (opcional)
    • query Record<string, string\> (optional) - Passed to url.format().
    • search string (opcional) - Pasado a url.format().
    • hash string (opcional) - Pasado a url.format().

Devuelve Promise<void> - la promesa sera resolvida cuando la página haya finalizado de cargar (mira did-finish-load), y será rechazada si la pagina falla al cargar (mira 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:

| root
| - package.json
| - src
| - main.js
| - index.html

Requeriría un código como este

const win = new BrowserWindow()
win.loadFile('src/index.html')

contents.downloadURL(url[, options])

  • url string
  • options Object (opcional)
    • headers Record<string, string\> (optional) - HTTP request headers.

Inicia una descarga del recurso en url sin navegar. The will-download event of session will be triggered.

contents.getURL()

Returns string - The URL of the current web page.

const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ width: 800, height: 600 })
win.loadURL('https://github.com').then(() => {
const currentURL = win.webContents.getURL()
console.log(currentURL)
})

contents.getTitle()

Returns string - The title of the current web page.

contents.isDestroyed()

Returns boolean - Whether the web page is destroyed.

contents.close([opts])

  • opts Object (optional)
    • 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.

contents.focus()

Enfoca la página web.

contents.isFocused()

Returns boolean - Whether the web page is focused.

contents.isLoading()

Returns boolean - Whether web page is still loading resources.

contents.isLoadingMainFrame()

Devuelve boolean - Si el marco principal (y no sólo iframes o frames dentro de él) todavía está cargando.

contents.isWaitingForResponse()

Devuelve boolean - Si la página web espera una primera respuesta desde el recurso principal de la página.

contents.stop()

Detiene cualquier navegación pendiente.

contents.reload()

Recarga la página web actual.

contents.reloadIgnoringCache()

Recarga la página actual e ignora el caché.

contents.canGoBack()

Devuelve boolean - Si el navegador puede volver a la página web anterior.

contents.canGoForward()

Devuelve boolean - Si el navegador puede avanzar a la siguiente página web.

contents.canGoToOffset(offset)

  • offset Íntegro

Devuelve boolean - Si la página web puede ir a offset.

contents.clearHistory()

Borra el historial de navegación.

contents.goBack()

Hace que el navegador regrese a una página web.

contents.goForward()

Hace que el navegador avance a una página web.

contents.goToIndex(index)

  • index Íntegro

Navega al índice de página web absoluta especificado.

contents.goToOffset(offset)

  • offset Íntegro

Navega hacia el offset especificado desde "la entrada actual".

contents.isCrashed()

Devuelve boolean - Si el proceso de renderizado ha fallado.

contents.forcefullyCrashRenderer()

Forzosamente termina el renderer process que actualmente aloja este webContents. Esto hará que sea emitido el evento render-process-gone con el reason=killed || reason=crashed. Tenga en cuenta que algunos webContents comparten el renderer process y por lo tanto llamar a este método puede causar que se bloque el proceso también para otros wevContents.

Llamar a reload() inmediatamente después de llamar a este método forzará que la recarga ocurra en un nuevo proceso. Esto debería ser usado cuando el proceso es inestable o inutilizable, por ejemplo parar recuperar del evento unresponsive.

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 cadena

Anula el agente usuario para esta página web.

contents.getUserAgent()

Devuelve string - El agente usuario para esta página web.

contents.insertCSS(css[, options])

  • css cadena
  • options Object (opcional)
    • cssOrigin string (optional) - Can be 'user' or 'author'. Sets the cascade origin of the inserted stylesheet. Default is 'author'.

Devuelve Promise<string> - Una promesa que resuelve con una llave para el CSS insertado que puede ser utilizado más tarde para eliminar el CSS a través contents.removeInsertedCSS(key).

Inyecta CSS en la página web actual y devuelve un identificador único para la hoja de estilo insertada.

const win = new BrowserWindow()
win.webContents.on('did-finish-load', () => {
win.webContents.insertCSS('html, body { background-color: #f00; }')
})

contents.removeInsertedCSS(key)

  • llave cadena

Devuelve Promise<void> - Resuelve si la eliminación fue exitosa.

Elimina el CSS insertado desde la página web actual. La hoja de estilos se identifica por su clave, el cual es devuelto desde 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])

  • codigo string
  • userGesture boolean (opcional) - Predeterminado es falso.

Devuelve Promise<any> - Una promesa que resuelve con el resultado de la ejecución del código o es rechazada si el resultado del código es una promesa rechazada.

Evalúa el código en la página.

En la ventana del navegador, algunas API HTML como requestFullScreen solo pueden invocarse con un gesto del usuario. Establecer userGesture a true eliminará esta limitación.

La ejecución de código se suspenderá hasta que la pagina pare de cargarse.

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 - El ID de la palabra para correr javascript en, 0 es el mundo por defecto, 999 es el mundo usado por la característica contextIsolation de Electron. Aquí puede suministrar cualquier entero.
  • scripts WebSource[]
  • userGesture boolean (opcional) - Predeterminado es falso.

Devuelve Promise<any> - Una promesa que resuelve con el resultado de la ejecución del código o es rechazada si el resultado del código es una promesa rechazada.

Funciona como executeJavaScript pero evaluá scripts en un contexto aislado.

contents.setIgnoreMenuShortcuts(ignore)

  • ignore boolean

Ignora los accesos directos del menú de la aplicación mientras se enfoca los contenidos de la web.

contents.setWindowOpenHandler(handler)

  • handler Function<{action: 'deny'} | {action: 'allow', outlivesOpener?: boolean, overrideBrowserWindowOptions?: BrowserWindowConstructorOptions}\>

    • details Object
      • url string - La versión resuelta de la URL pasada a window.open(). por ejemplo una ventana con window.open('foo') producirá algo como https://the-origin/the/current/path/foo.
      • frameName string - Nombre de la ventana proporcionado en window.open()
      • features string - Lista separada por coma de la características de ventana proporcionada a window.open().
      • disposition string - Can be default, foreground-tab, background-tab, new-window or other.
      • referrer Referrer - The referrer that will be passed to the new window. Puede resultar o no en la cabecera Referer siendo enviado, dependiendo de la política de referencia.
      • postBody PostBody (opcional) - Los datos que serán enviados a la nueva ventana, junto con las cabeceras apropiadas que se establecerán. Si no hay datos para enviar, el valor será null. Solo se define cuando la ventana está siendo creada por un formulario que establece target=_blank.

    Devuelve {action: 'deny'} | {action: 'allow', outlivesOpener?: boolean, overrideBrowserWindowOptions?: BrowserWindowConstructorOptions} - deny cancela la creación de la nueva ventana. allow permitirá la que se cree la nueva ventana. Especificando overrideBrowserWindowOptions permite la personalización de la ventana creada. By default, child windows are closed when their opener is closed. This can be changed by specifying outlivesOpener: true, in which case the opened window will not be closed when its opener is closed. Devolver un valor no reconocido como un null, undefined o un objeto sin una 'action' reconocida resultará en un error de consola tiene el mismo efecto que devolver {action: 'deny'}.

Llamado antes de crear una ventana un solicitud de nueva ventana es solicitada por el renderer, p.e. por window.open(), un enlace con target="_blank", shift+pulsando en un enlace, o enviando un formulario con <form target="_blank">. Ver window.open() Para más detalles y como usar esto en conjunción con did-create-window.

contents.setAudioMuted(muted)

  • muted boolean

Silencia el audio la página web actual.

contents.isAudioMuted()

Devuelve boolean - Si esta página ha sido silenciada.

contents.isCurrentlyAudible()

Devuelve boolean - Si el audio se esta reproduciendo actualmente.

contents.setZoomFactor(factor)

  • factor Double - Factor de zoom; por defecto es 1.0.

Cambia el nivel de zoom al nivel especificado. Factor de zoom es porcentaje de zoom dividido entre 100, así que 300% = 3.0.

El factor debe ser mayor que 0.0.

contents.getZoomFactor()

Devuelve number - el factor de zoom actual.

contents.setZoomLevel(level)

  • nivel número - Nivel de Zoom.

Cambia el nivel de zoom al nivel especificado. El tamaño original es 0 y cada incremento por encima o por debajo representa un zoom del 20% mayor o menor a los límites predeterminados de 300% y 50% del tamaño original, respectivamente. La fórmula para esto es 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.

contents.getZoomLevel()

Devuelve number - el nivel de zoom actual.

contents.setVisualZoomLevelLimits(minimumLevel, maximumLevel)

  • minimumLevel número
  • maximumLevel número

Devuelve Promise<void>

Establecer el nivel de máximo y mínimo pizca de zoom.

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

Ejecuta el comando de edición undo en la página web.

contents.redo()

Ejecuta el comando de edición redo en la página web.

contents.cut()

Ejecuta el comando de edición cut en la página web.

contents.copy()

Ejecuta el comando de edición copy en la página web.

contents.centerSelection()

Centers the current text selection in web page.

contents.copyImageAt(x, y)

  • x Integer
  • y Integer

Copia la imagen en la posición determinada al portapapeles.

contents.paste()

Ejecuta el comando de edición paste en la página web.

contents.pasteAndMatchStyle()

Ejecuta el comando de edición pasteAndMatchStyle en la página web.

contents.delete()

Ejecuta el comando de edición delete en la página web.

contents.selectAll()

Ejecuta el comando de edición selectAll en la página web.

contents.unselect()

Ejecuta el comando de edición unselect en la página web.

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.

Ejemplo:

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)

  • texto cadena

Ejecuta el comando de edición replace en la página web.

contents.replaceMisspelling(text)

  • texto cadena

Ejecuta el comando de edición replaceMisspelling en página web.

contents.insertText(text)

  • texto cadena

Devuelve Promise<void>

Inserta texto en el elemento enfocado.

contents.findInPage(text[, options])

  • text string - El contenido para ser buscado, no debe quedar en blanco.
  • options Object (opcional)
    • forward boolean (opcional) - Ya sea para buscar hacia adelante o hacia atrás, el valor predeterminado es 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. Por defecto es false.
    • matchCase boolean (opcional) - Si la busqueda debe ser sensible a mayúsculas, por defecto es false.

Devuelve Integer - El id de la solicitud usado para la solicitud.

Empieza una solicitud para encontrar todas las coincidencias para el text en la página web. El resultado de la petición puede ser obtenido por suscripción al evento found-in-page.

contents.stopFindInPage(action)

  • action string - Specifies the action to take place when ending webContents.findInPage request.
    • clearSelection - Borrar la selección.
    • keepSelection - Traduce la selección en una selección normal.
    • activateSelection - Enfoca y hace clic en el nodo de selección.

Detiene cualquier solicitud findInPage para el webContents con la action proporcionada.

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

  • rect Rectangle (opcional) - El área de la página para ser capturada.
  • opts Object (optional)
    • stayHidden boolean (opcional) - Mantiene la página oculta en lugar de visible. Por defecto es false.
    • stayAwake boolean (optional) - Keep the system awake instead of allowing it to sleep. Por defecto es false.

Devuelve Promise<NativeImage> - Resuelve con el un NativeImage

Captura una foto instantánea de la página dentro de rect. Omitir rect capturará toda la página visible. The page is considered visible when its browser window is hidden and the capturer count is non-zero. Si le gustaría que la página permanezca oculta, debería asegurarse que stayHidden está establecido a true.

contents.isBeingCaptured()

Devuelve boolean - Si esta página está siendo capturada. Devuelve true cuando el recuento de capturadores es mas grande que 0.

contents.getPrintersAsync()

Obtiene la lista de impresora del sistema.

Devuelve Promise<PrinterInfo[]> - Resuelve con un PrinterInfo[]

contents.print([options], [callback])

  • options Object (opcional)
    • silent boolean (optional) - Don't ask user for print settings. Por defecto es false.
    • printBackground boolean (optional) - Prints the background color and image of the web page. Por defecto es 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. Por defecto es true.
    • margins Object (opcional)
      • marginType string (opcional) - Puede ser default, none, printableArea, o custom. Si custom es elegido, además necesitar especificar top, bottom, left, y right.
      • top number (opcional) - El margen superior de la página web impresa, en píxeles.
      • bottom number (opcional) - El margen inferior de la página web impresa, en píxeles.
      • left number (opcional) - El margen izquierdo de la página web impresa, en píxeles.
      • right number (opcional) - El margen derecho de la página web impresa, en píxeles.
    • landscape boolean (optional) - Whether the web page should be printed in landscape mode. Por defecto es false.
    • scaleFactor number (opcional) - El factor de escalado de la página web.
    • pagesPerSheet number (opcional) - El número de páginas a imprimir por hoja de página.
    • collate boolean (opcional) - Si la página web debe ser intercalada.
    • copies number (opcional) - El número de copias de la página web a imprimir.
    • 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 - Índice de la última página a imprimir (inclusive) (0-based).
    • duplexMode string (optional) - Set the duplex mode of the printed web page. Puede ser simplex, shortEdge, o longEdge.
    • dpi Record<string, number\> (optional)
      • horizontal number (opcional) - El dpi horizontal.
      • vertical number (opcional) - El dpi vertical.
    • header string (opcional) - Cadena a ser impresa como cabecera de la página.
    • footer string (opcional) - Cadena a ser impresa como pie de página.
    • pageSize string | Tamaño (opcional) - Especifique el tamaño de página del documento impreso. Can be A0, A1, A2, A3, A4, A5, A6, Legal, Letter, Tabloid or an Object containing height and width.
  • retrocallback Funcion (opcional)
    • success boolean - Indica el éxito de la llamada impresa.
    • failureReason string - Descripción del error llamada de nuevo si la impresión falla.

Cuando es pasado un pageSize personalizado, Chromium intenta validar los valores mínimos específicos de la plataforma para width_microns y height_microns. Ambos anchura y altura deben ser mínimamente 353 microns, pero puede ser más grande en algunos sistemas operativos.

Imprime la página web de la ventana. Cuando silent es establecido a true, Electron tomará la impresora por defecto del sistema si deviceName está vacío y la configuraciones por defecto para imprimir.

Utilizar el estilo CCS page-break-before: always; para imprimir a la fuerza una página nueva.

Ejemplo de uso:

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

contents.printToPDF(options)

  • options Object
    • landscape boolean (optional) - Paper orientation.true for landscape, false for portrait. Por defecto es falso.
    • displayHeaderFooter boolean (optional) - Whether to display header and footer. Por defecto es falso.
    • printBackground boolean (optional) - Whether to print background graphics. Por defecto es falso.
    • scale number(optional) - Scale of the webpage rendering. Defaults to 1.
    • pageSize string | Size (opcional) - Especifique el tamaño de la pagina PDF generada. Can be A0, A1, A2, A3, A4, A5, A6, Legal, Letter, Tabloid, Ledger, or an Object containing height and width in inches. Por defecto es Letter.
    • margins Object (opcional)
      • 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. Por defecto es falso. 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. Por defecto es falso.

Returns Promise<Buffer> - Se resuelve cuando los datos PDF son generados.

Prints the window's web page as PDF.

El landscape se ignorará si @page CSS at-rule es utilizado en la página web.

Un ejemplo de webContents.printToPDF:

const { app, BrowserWindow } = require('electron')
const fs = require('node:fs')
const path = require('node:path')
const os = require('node:os')

app.whenReady().then(() => {
const win = new BrowserWindow()
win.loadURL('https://github.com')

win.webContents.on('did-finish-load', () => {
// Use default printing options
const pdfPath = path.join(os.homedir(), 'Desktop', 'temp.pdf')
win.webContents.printToPDF({}).then(data => {
fs.writeFile(pdfPath, data, (error) => {
if (error) throw error
console.log(`Wrote PDF successfully to ${pdfPath}`)
})
}).catch(error => {
console.log(`Failed to write PDF to ${pdfPath}: `, error)
})
})
})

See Page.printToPdf for more information.

contents.addWorkSpace(path)

  • path string

Agrega la ruta especificada al workspace de DevTools. Debe ser usado después de la creación de DevTools:

const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
win.webContents.on('devtools-opened', () => {
win.webContents.addWorkSpace(__dirname)
})

contents.removeWorkSpace(path)

  • path string

Elimina la ruta especificada del espacio de trabajo de DevTools.

contents.setDevToolsWebContents(devToolsWebContents)

  • devToolsWebContents WebContents

Usa el devToolsWebContents como objetivo WebContents para mostrar devtools.

El devToolsWebContents no debe tener ninguna ninguna navegación, y este no debería ser usado para otros propósitos después de la llamada.

Por defecto Electron maneja el devtools creando un WebContents interno con un vista nativa, de lo cual los desarrolladores tienen un control muy limitado. Con el método setDevToolsWebContents, los desarrolladores pueden usar algún WebContents para mostrar el devtools en él, incluyendo la etiqueta BrowserWindow, BrowserView y <webview>.

Tenga en cuenta que cerrando el devtools no se destruye el devToolsWebContents, es responsabilidad del que llamo destruir el devToolsWebContents.

Un ejemplo de mostrar devtools en una etiqueta <webview>:

<html>
<head>
<style type="text/css">
* { margin: 0; }
#browser { height: 70%; }
#devtools { height: 30%; }
</style>
</head>
<body>
<webview id="browser" src="https://github.com"></webview>
<webview id="devtools" src="about:blank"></webview>
<script>
const { ipcRenderer } = require('electron')
const emittedOnce = (element, eventName) => new Promise(resolve => {
element.addEventListener(eventName, event => resolve(event), { once: true })
})
const browserView = document.getElementById('browser')
const devtoolsView = document.getElementById('devtools')
const browserReady = emittedOnce(browserView, 'dom-ready')
const devtoolsReady = emittedOnce(devtoolsView, 'dom-ready')
Promise.all([browserReady, devtoolsReady]).then(() => {
const targetId = browserView.getWebContentsId()
const devtoolsId = devtoolsView.getWebContentsId()
ipcRenderer.send('open-devtools', targetId, devtoolsId)
})
</script>
</body>
</html>
// Main process
const { ipcMain, webContents } = require('electron')
ipcMain.on('open-devtools', (event, targetContentsId, devtoolsContentsId) => {
const target = webContents.fromId(targetContentsId)
const devtools = webContents.fromId(devtoolsContentsId)
target.setDevToolsWebContents(devtools)
target.openDevTools()
})

Un ejemplo de mostrar devtools en un BrowserWindow:

main.js
const { app, BrowserWindow } = require('electron')

let win = null
let devtools = null

app.whenReady().then(() => {
win = new BrowserWindow()
devtools = new BrowserWindow()
win.loadURL('https://github.com')
win.webContents.setDevToolsWebContents(devtools.webContents)
win.webContents.openDevTools({ mode: 'detach' })
})

contents.openDevTools([options])

  • options Object (opcional)
    • mode string - Opens the devtools with specified dock state, can be left, right, bottom, undocked, detach. Por defecto se utiliza el último estado de dock. En el modo undocked es posible acoplarse de nuevo. En el modo detach no se puede.
    • activate boolean (optional) - Whether to bring the opened devtools window to the foreground. El valor por defecto es true.
    • title string (optional) - A title for the DevTools window (only in undocked or detach mode).

Abre las herramientas del desarrolador.

Cuando contents es un tag <webview>, el mode debería ser detach por defecto, explícitamente pasando un mode vacío puede forzar el uso del último estado del dock.

On Windows, if Windows Control Overlay is enabled, Devtools will be opened with mode: 'detach'.

contents.closeDevTools()

Cierra las devtools.

contents.isDevToolsOpened()

Devuelve boolean - Si se abren las herramientas del desarrollador.

contents.isDevToolsFocused()

Devuelve boolean - Si se enfoca la vista de las herramientas del desarrollador .

contents.getDevToolsTitle()

Returns string - the current title of the DevTools window. This will only be visible if DevTools is opened in undocked or detach mode.

contents.setDevToolsTitle(title)

  • title string

Changes the title of the DevTools window to title. This will only be visible if DevTools is opened in undocked or detach mode.

contents.toggleDevTools()

Alterna las herramientas de desarrollador.

contents.inspectElement(x, y)

  • x Integer
  • y Integer

Empieza a inspeccionar elementos en la posición (x, y).

contents.inspectSharedWorker()

Abre las herramientas de desarrollador para el contexto de los trabajadores compartidos.

contents.inspectSharedWorkerById(workerId)

  • cadena workerId

Inspecciona el shared worker basado en su ID.

contents.getAllSharedWorkers()

Returns SharedWorkerInfo[] - Information about all Shared Workers.

contents.inspectServiceWorker()

Abre las herramientas de desarrollador para el contexto del trabajador de servicio.

contents.send(channel, ...args)

  • channel cadena
  • ...args any[]

Envía un mensaje asíncrono al render process a través de channel, junto con los argumentos. Arguments will be serialized with the Structured Clone Algorithm, just like postMessage, so prototype chains will not be included. El envío de funciones, promesas, símbolos, WeakMaps o WeakSets lanzará una excepción.

:::advertencia

Sending non-standard JavaScript types such as DOM objects or special Electron objects will throw an exception.

:::

For additional reading, refer to Electron's IPC guide.

contents.sendToFrame(frameId, channel, ...args)

  • 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 cadena
  • ...args any[]

Envía un mensaje asíncrono al frame especifico en un renderer process a través de channel, junto con los argumentos. Arguments will be serialized with the Structured Clone Algorithm, just like postMessage, so prototype chains will not be included. El envío de funciones, promesas, símbolos, WeakMaps o WeakSets lanzará una excepción.

NOTA: Enviar tipos de JavaScript no estándar tales como objetos DOM o objetos especiales de Electron lanzará una excepción.

El proceso de renderizado puede manejar el mensaje escuchando el canal con el módulo ipcRenderer.

Si quieres obtener el frameId de un renderer context dado deberías usar el valor webFrame.routingId. P.e.

// In a renderer process
console.log('My frameId is:', require('electron').webFrame.routingId)

También puede leer el frameId de todos los mensajes IPC entrantes en el proceso principal.

// In the main process
ipcMain.on('ping', (event) => {
console.info('Message came from frameId:', event.frameId)
})

contents.postMessage(channel, message, [transfer])

  • channel cadena
  • mensaje cualquiera
  • transfer MessagePortMain[] (optional)

Send a message to the renderer process, optionally transferring ownership of zero or more MessagePortMain objects.

Los objetos MessagePortMain transferidos estarán disponible en el renderer process accediendo a la propiedad ports del evento emitido. Cuando llegan al renderer, serán objetos DOM MessagePort nativos.

Por ejemplo:

// Main process
const win = new BrowserWindow()
const { port1, port2 } = new MessageChannelMain()
win.webContents.postMessage('port', { message: 'hello' }, [port1])

// Renderer process
ipcRenderer.on('port', (e, msg) => {
const [port] = e.ports
// ...
})

contents.enableDeviceEmulation(parameters)

  • parameters Object
    • screenPosition string - Specify the screen type to emulate (default: desktop):
      • desktop - El tipo de la pantalla de escritorio.
      • mobile - El tipo de la pantalla móvil.
    • screenSize Size - Set the emulated screen size (screenPosition == mobile).
    • viewPosition Point - Position the view on the screen (screenPosition == mobile) (default: { x: 0, y: 0 }).
    • deviceScaleFactor Integer - Configura el factor escala del dispositivo (si es cero regresa por defecto al factor de escala original del dispositivo) (por defecto: 0).
    • viewSize Size - Set the emulated view size (empty means no override)
    • scale Float - Escala de la vista emulada dentro del espacio disponible (no dentro del modo vista) (por defecto: 1).

Habilita la emulación del dispositivo con los parámetros predeterminados.

contents.disableDeviceEmulation()

Deshabilita la emulación del dispositivo habilitado por webContents.enableDeviceEmulation.

contents.sendInputEvent(inputEvent)

Envía un input event a la página. Note: The BrowserWindow containing the contents needs to be focused for sendInputEvent() to work.

contents.beginFrameSubscription([onlyDirty ,]callback)

  • onlyDirty boolean (opcional) - Por defecto es false.
  • callback Function

Empezar suscripción para eventos de presentación y capturas de fotogramas, la callback sera llamada con callback(image, dirtyRect) cuando hay un evento de presentación.

The image is an instance of NativeImage that stores the captured frame.

El dirtyRect es un objeto con propiedades x, y, width, height que describe cual parte de la página fue pintada de nuevo. Si onlyDirty está configurado a true, image solo contendrá el área repintada. onlyDirty por defecto en false.

contents.endFrameSubscription()

Finalizar suscripción para eventos de presentación de marcos.

contents.startDrag(item)

  • Objeto item
    • file string - La ruta al archivo que está siendo arrastrado.
    • files string[] (opcional) - Las rutas a los archivos que están siendo arrastrados. (files anulará el campo file)
    • icon NativeImage | string - The image must be non-empty on macOS.

Configura el item como un elemento arrastrable para la operación drag-drop actual. El file es la ruta absoluta del archivo que se va a arrastrar, y icon es la imagen que se muestra debajo del cursor cuando se arrastra.

contents.savePage(fullPath, saveType)

  • fullPath string - The absolute file path.
  • saveType string - Specify the save type.
    • HTMLOnly - Guarda solamente el HTML de la página.
    • HTMLComplete - Guarda una página html completa.
    • MHTML - Guarda una página html completa como MHTML.

Devuelve Promise<void> - resuelve si la pagina se guardo.

const { BrowserWindow } = require('electron')
const win = new BrowserWindow()

win.loadURL('https://github.com')

win.webContents.on('did-finish-load', async () => {
win.webContents.savePage('/tmp/test.html', 'HTMLComplete').then(() => {
console.log('Page was saved successfully.')
}).catch(err => {
console.log(err)
})
})

contents.showDefinitionForSelection() macOS

Muestra un diccionario que busca la palabra seleccionada en la página.

contents.isOffscreen()

Devuelve boolean - Indica si offscreen rendering está habilitado o no.

contents.startPainting()

Si offscreen rendering está habilitado y no pinta, comienza a pintar.

contents.stopPainting()

Si offscreen rendering está habilitado y pinta, deja de pintar.

contents.isPainting()

Devuelve boolean - Si offscreen rendering está habilitado devuelve lo que esté pintando en ese momento.

contents.setFrameRate(fps)

  • fps Integer

Si offscreen rendering está activada establece el radio del frame al número especificado. Sólo se aceptan valores entre 1 y 240.

contents.getFrameRate()

Devuelve Integer - Si offscreen rendering esta habilitado devuelve el indice de fotogramas en ese momento.

contents.invalidate()

Programa un repintado completo de la ventana en la que se encuentra este contenido web.

Si offscreen rendering está habilitado invalida el fotograma y genera uno nuevo a través del evento 'paint'.

contents.getWebRTCIPHandlingPolicy()

Devuelve string - Devuelve el WebRTC IP Handling Policy.

contents.setWebRTCIPHandlingPolicy(policy)

  • policy string - Specify the WebRTC IP Handling Policy.
    • default - Revela los IPs locales y publicos del usuario. Este es el comportamiento por defecto. Cuando se usa esta política, WebRTC tiene el derecho de enumerar todas las interfaces y vincularlas para descubrir interfaces públicas.
    • default_public_interface_only - Revela el IP público del usuario pero no revela el IP local del usuario. Cuando se usa esta política, WebRTC solo debe usar la ruta predeterminada utilizada por http. Esto no expone ninguna dirección local.
    • default_public_and_private_interfaces - Revela los IPs público y local del usuario. Cuando se usa esta política, WebRTC solo debe usar la ruta predeterminada utilizada por http. Esto también expone la dirección privada predeterminada asociada. La ruta predeterminada es la ruta elegida por el SO en un punto final multitarjeta.
    • 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.

La configuración de política de manejo WebRTC IP, le permite controlar cuales IPs son expuestas a través de WebRTC. Vea BrowserLeaks para más detalles.

contents.getWebRTCUDPPortRange()

Devuelve Objeto:

  • min Integer - The minimum UDP port number that WebRTC should use.
  • max Integer - The maximum UDP port number that WebRTC should use.

By default this value is { min: 0, max: 0 } , which would apply no restriction on the udp port range.

contents.setWebRTCUDPPortRange(udpPortRange)

  • udpPortRange Object
    • 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 }.

contents.getMediaSourceId(requestWebContents)

  • requestWebContents WebContents - Web contents that the id will be registered to.

Devuelve string - El identificador de un flujo de WebContents. Este identificador puede ser usado con navigator.mediaDevices.getUserMedia usando un chromeMediaSource de tab. Este identificador está restringido al web contents al cual está registrado y solo es válido por 10 segundos.

contents.getOSProcessId()

Devuelve Integer - El pid del sistema operativo, del proceso de renderizado asociado.

contents.getProcessId()

Devuelve Integer - El pid interno de Chromium del renderizador asociado. Puede ser comparado con el frameProcessId pasado por los eventos de navegación específicos del frame (e.g. did-frame-navigate)

contents.takeHeapSnapshot(filePath)

  • filePath string - Ruta al archivo de salida.

Devuelve Promise<void> - Indica si la instantánea se ha creado correctamente.

Toma una instantánea de la pila V8 y la guarda en filePath.

contents.getBackgroundThrottling()

Devuelve boolean - si este contenido web acelerará o no animaciones y temporizadores cuando la página se haga de fondo. Esto también afecta a la API de visibilidad de la página.

contents.setBackgroundThrottling(allowed)

  • allowed boolean

Controla si este WebContents acelerará o no las animaciones y los temporizadores cuando la página pasa a segundo plano. Esto también afecta a la API de visibilidad de la página.

contents.getType()

Devuelve string - el tipo de webContent. Puede ser backgroundPage, window, browserView, remote, webview o offscreen.

contents.setImageAnimationPolicy(policy)

  • policy string - Puede ser animate, animateOnce o noAnimation.

Establece la política de animación de imágenes para este webContents. La política solo afecta a imágenes new, las imágenes que se está animando actualmente no son afectadas. Esta es una limitación conocida en Chromium, puede forzar que la animación de la imagen sea recalculada con img.src = img.src lo cual no dará como resultado tráfico de red pero actualizará la política de la animación.

Esto corresponde a la característica de accesibilidad animationPolicy en Chromium.

Propiedades de la instancia

contents.ipc Readonly

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:

  1. contents.on('ipc-message')
  2. contents.mainFrame.on(channel)
  3. contents.ipc.on(channel)
  4. 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.

  1. contents.mainFrame.handle(channel)
  2. contents.handle(channel)
  3. 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.

contents.audioMuted

Una propiedad boolean que determina si esta página esta silenciada o no.

contents.userAgent

Una propiedad string que determina el agente de usuario para esta página web.

contents.zoomLevel

Una propiedad number que determina el nivel de zoom para web contents.

El tamaño original es 0 y en cada incremento arriba o abajo representa un 20% más grande o más pequeño para los limites por defecto que son de 300% y 50% del tamaño original respectivamente. La fórmula para esto es scale := 1.2 ^ level.

contents.zoomFactor

Una propiedad number que determina el facto de zoom para este web contents.

El factor de zoom es el porcentaje de zoom dividido por 100, así que 300% = 3.0.

contents.frameRate

Una propiedad Integer que establece el ratio del frame del contenido web al número especificado. Sólo se aceptan valores entre 1 y 240.

Sólo aplicable si offscreen rendering está activado.

contents.id Readonly

Un Integer representando el ID único de este WebContents. Cada ID es único entre todas las instancias WebContents de toda la aplicación Electron.

contents.session Readonly

Un Session usado por este webContents.

contents.navigationHistory SoloLectura

Un NavigationHistory usado por este webContents.

contents.hostWebContents Readonly

Un instancia de WebContents que podría poseer este WebContents.

contents.devToolsWebContents Readonly

Una propiedad WebContents | null que representa el WebContents de la DevTools asociada con el WebContents dado.

Note: Los usuario nunca deberían almacenar este objeto porque puede convertirse en null cuando el DevTools ha sido cerrado.

contents.debugger Readonly

Una instancia Debugger para este webContents.

contents.backgroundThrottling

Una propiedad boolean que determina si este WebContents acelera o no las animaciones y los temporizadores cuando la página pasa a segundo plano. Esto también afecta a la API de visibilidad de la página.

contents.mainFrame Readonly

A WebFrameMain property that represents the top frame of the page's frame hierarchy.

contents.opener Readonly

A WebFrameMain property that represents the frame that opened this WebContents, either with open(), or by navigating a link with a target attribute.