webContents
Procesamiento y control de páginas webs.
Proceso: principal
webContents es un EventEmitter. It is responsible for rendering and controlling a web page and is a property of the BrowserWindow object. 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)
Navigation Events
Several events can be used to monitor navigations as they occur within a webContents.
Document Navigations
When a webContents navigates to another page (as opposed to an in-page navigation), the following events will be fired.
did-start-navigationwill-frame-navigatewill-navigate(only fired when main frame navigates)will-redirect(only fired when a redirect happens during navigation)did-redirect-navigation(only fired when a redirect happens during navigation)did-frame-navigatedid-navigate(only fired when main frame navigates)
Subsequent events will not fire if event.preventDefault() is called on any of the cancellable events.
In-page Navigation
In-page navigations don't cause the page to reload, but instead navigate to a location within the current page. These events are not cancellable. For an in-page navigations, the following events will fire in this order:
Frame Navigation
The will-navigate and did-navigate events only fire when the mainFrame navigates. If you want to also observe navigations in <iframe>s, use will-frame-navigate and did-frame-navigate events.
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)
frameWebFrameMain
Returns WebContents | undefined - A WebContents instance with the given WebFrameMain, or undefined if there is no WebContents associated with the given WebFrameMain.
webContents.fromDevToolsTargetId(targetId)
targetIdstring - The Chrome DevTools Protocol TargetID associated with the WebContents instance.
Returns WebContents | undefined - A WebContents instance with the given TargetID, or undefined if there is no WebContents associated with the given TargetID.
When communicating with the Chrome DevTools Protocol, it can be useful to lookup a WebContents instance based on its assigned TargetID.
async function lookupTargetId (browserWindow) {
const wc = browserWindow.webContents
await wc.debugger.attach('1.3')
const { targetInfo } = await wc.debugger.sendCommand('Target.getTargetInfo')
const { targetId } = targetInfo
const targetWebContents = await wc.fromDevToolsTargetId(targetId)
}
Clase: WebContents
Renderice y controle el contenido de una instancia de BrowserWindow.
Process: Main
This class is not exported from the 'electron' module. 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:
eventerrorCodeIntegererrorDescriptionstringvalidatedURLstringisMainFramebooleanframeProcessIdIntegerframeRoutingIdEntero
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:
eventerrorCodeIntegererrorDescriptionstringvalidatedURLstringisMainFramebooleanframeProcessIdIntegerframeRoutingIdEntero
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:
eventisMainFramebooleanframeProcessIdIntegerframeRoutingIdEntero
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:
eventtitlestringexplicitSetboolen
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:
eventfaviconsstring[] - matriz de URLs.
Emite cuando la página recibe urls de favicon.
Event: 'content-bounds-updated'
Devuelve:
eventboundsRectangle - 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:
windowNavegador WindowsdetailsObjecturlstring - URL for the created window.frameNamestring - Name given to the created window in thewindow.open()call.referrerReferrer - The referrer that will be passed to the new window. Puede resultar o no en la cabeceraReferersiendo enviado, dependiendo de la política de referencia.postBodyPostBody (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 settarget=_blank.dispositionstring - Can bedefault,foreground-tab,background-tab,new-windoworother.
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:
detailsEvent<>urlstring - The URL the frame is navigating to.isSameDocumentboolean - This event does not fire for same document navigations using window.history api and reference fragment navigations. This property is always set tofalsefor this event.isMainFrameboolean - True if the navigation is taking place in a main frame.frameWebFrameMain | null - The frame to be navigated. May benullif accessed after the frame has either navigated or been destroyed.initiatorWebFrameMain | null (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. viawindow.openwith 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.
urlstring DeprecatedisInPlaceboolean DeprecatedisMainFrameboolean DeprecatedframeProcessIdInteger DeprecatedframeRoutingIdInteger 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:
detailsEvent<>urlstring - The URL the frame is navigating to.isSameDocumentboolean - This event does not fire for same document navigations using window.history api and reference fragment navigations. This property is always set tofalsefor this event.isMainFrameboolean - True if the navigation is taking place in a main frame.frameWebFrameMain | null - The frame to be navigated. May benullif accessed after the frame has either navigated or been destroyed.initiatorWebFrameMain | null (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. viawindow.openwith 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:
detailsEvent<>urlstring - The URL the frame is navigating to.isSameDocumentboolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation.isMainFrameboolean - True if the navigation is taking place in a main frame.frameWebFrameMain | null - The frame to be navigated. May benullif accessed after the frame has either navigated or been destroyed.initiatorWebFrameMain | null (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. viawindow.openwith 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.
urlstring DeprecatedisInPlaceboolean DeprecatedisMainFrameboolean DeprecatedframeProcessIdInteger DeprecatedframeRoutingIdInteger Deprecated
Emitido cuando cualquier frame (incluyendo el principal) comienza la navegación.
Evento: 'will-redirect'
Devuelve:
detailsEvent<>urlstring - The URL the frame is navigating to.isSameDocumentboolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation.isMainFrameboolean - True if the navigation is taking place in a main frame.frameWebFrameMain | null - The frame to be navigated. May benullif accessed after the frame has either navigated or been destroyed.initiatorWebFrameMain | null (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. viawindow.openwith 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.
urlstring DeprecatedisInPlaceboolean DeprecatedisMainFrameboolean DeprecatedframeProcessIdInteger DeprecatedframeRoutingIdInteger 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:
detailsEvent<>urlstring - The URL the frame is navigating to.isSameDocumentboolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation.isMainFrameboolean - True if the navigation is taking place in a main frame.frameWebFrameMain | null - The frame to be navigated. May benullif accessed after the frame has either navigated or been destroyed.initiatorWebFrameMain | null (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. viawindow.openwith 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.
urlstring DeprecatedisInPlaceboolean DeprecatedisMainFrameboolean DeprecatedframeProcessIdInteger DeprecatedframeRoutingIdInteger 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:
eventurlstringhttpResponseCodeInteger - -1 para navegaciones no HTTPhttpStatusTextstring - 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:
eventurlstringhttpResponseCodeInteger - -1 para navegaciones no HTTPhttpStatusTextstring - empty for non HTTP navigations,isMainFramebooleanframeProcessIdIntegerframeRoutingIdEntero
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:
eventurlstringisMainFramebooleanframeProcessIdIntegerframeRoutingIdEntero
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:
eventdetailsRenderProcessGoneDetails
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:
eventnamestringversioncadena
Emitido cuando el proceso de enchufe se ha caído.
Evento: 'destroyed'
Emitido cuando webContents es destruido.
Event: 'input-event'
Devuelve:
eventinputEventInputEvent
Emitted when an input event is sent to the WebContents. See InputEvent for details.
Evento: 'before-input-event'
Devuelve:
eventinputObject - Input properties.typestring - EitherkeyUporkeyDown.keystring - Equivalent to KeyboardEvent.key.codestring - Equivalent to KeyboardEvent.code.isAutoRepeatboolean - Equivalent to KeyboardEvent.repeat.isComposingboolean - Equivalent to KeyboardEvent.isComposing.shiftboolean - Equivalent to KeyboardEvent.shiftKey.controlboolean - Equivalent to KeyboardEvent.controlKey.altboolean - Equivalent to KeyboardEvent.altKey.metaboolean - Equivalent to KeyboardEvent.metaKey.locationnumber - Equivalent to KeyboardEvent.location.modifiersstring[] - See InputEvent.modifiers.
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:
eventzoomDirectionstring - Can beinorout.
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:
eventurlstring - 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:
eventquerystring - 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:
eventurlstringerrorcadena - el error del código.certificateCertificatecallbackFunctionisTrustedboolean - indica si el certificado se puede considerar de confianza.
isMainFrameboolean
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:
eventurlURLcertificateListCertificate[]callbackFunctioncertificateCertificate - Must be a certificate from the given list.
Emitido cuando el certificado de un cliente es requerido.
El uso es lo mismo que con el evento the select-client-certificate de la app.
Evento:'login'
Devuelve:
eventauthenticationResponseDetailsObjecturlURL
authInfoObject- Booleano
isProxy - Cadena
scheme - Cadena
host puertoÍntegro- Cadena
realm
- Booleano
callbackFunction- Cadena
username(opcional) - Cadena
password(opcional)
- Cadena
Emitido cuando webContents quiere hacer una autenticación básica.
The usage is the same with the login event of app.
Evento: 'found-in-page'
Devuelve:
event- Objeto
resultrequestIdÍntegroactiveMatchOrdinalÍntegro - Posición de un partido activo.matchesÍntegro - Número de Coincidencias.selectionAreaRectangle - Coordenadas de la primera región de coincidencia.finalUpdateboolean
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:
eventEvent<>audibleboolean - True if one or more frames or childwebContentsare emitting audio.
Emitted when media becomes audible or inaudible.
Evento: 'did-change-theme-color'
Devuelve:
eventcolor(string | null) - Theme color is in format of '#rrggbb'. It isnullwhen no theme color is set.
Emitted when a page's theme color changes. This is usually due to encountering a meta tag:
<meta name='theme-color' content='#ff0000'>
Evento: 'update-target-url'
Devuelve:
eventurlstring
Emitido cuando el mouse se mueve sobre un link o el teclado se mueve el concentrado a un link.
Evento: 'cursor-changed'
Devuelve:
eventtypestringimageNativeImage (optional)scaleFloat (opcional) - Factor de escala para el cursor personalizado.sizeSize (optional) - the size of theimage.hotspotPoint (optional) - coordinates of the custom cursor's hotspot.
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:
eventparamsObjectxInteger - x coordinate.yInteger - y coordinate.frameWebFrameMain | null - Frame from which the context menu was invoked. May benullif accessed after the frame has either navigated or been destroyed.linkURLstring - URL of the link that encloses the node the context menu was invoked on.linkTextstring - Text associated with the link. May be an empty string if the contents of the link are an image.pageURLstring - URL of the top level page that the context menu was invoked on.frameURLstring - URL of the subframe that the context menu was invoked on.srcURLstring - Source URL for the element that the context menu was invoked on. Elements with source URLs are images, audio and video.mediaTypestring - Type of the node the context menu was invoked on. Puede sernone,image,audio,video,canvas,fileoplugin.hasImageContentsboolean - Whether the context menu was invoked on an image which has non-empty contents.isEditableboolean - Whether the context is editable.selectionTextstring - Text of the selection that the context menu was invoked on.titleTextstring - Title text of the selection that the context menu was invoked on.altTextstring - Alt text of the selection that the context menu was invoked on.suggestedFilenamestring - Suggested filename to be used when saving file through 'Save Link As' option of context menu.selectionRectRectangle - Rect representing the coordinates in the document space of the selection.selectionStartOffsetnumber - Start position of the selection text.referrerPolicyReferrer - The referrer policy of the frame on which the menu is invoked.misspelledWordstring - The misspelled word under the cursor, if any.dictionarySuggestionsstring[] - An array of suggested words to show the user to replace themisspelledWord. Solo disponible si hay una palabra mal escrita y el corrector está habilitado.frameCharsetstring - The character encoding of the frame on which the menu was invoked.formControlTypestring - The source that the context menu was invoked on. Possible values includenone,button-button,field-set,input-button,input-checkbox,input-color,input-date,input-datetime-local,input-email,input-file,input-hidden,input-image,input-month,input-number,input-password,input-radio,input-range,input-reset,input-search,input-submit,input-telephone,input-text,input-time,input-url,input-week,output,reset-button,select-list,select-list,select-multiple,select-one,submit-button, andtext-area,spellcheckEnabledboolean - If the context is editable, whether or not spellchecking is enabled.menuSourceTypestring - Input source that invoked the context menu. Puede sernone,mouse,keyboard,touch,touchMenu,longPress,longTap,touchHandle,stylus,adjustSelection, oadjustSelectionReset.mediaFlagsObject - The flags for the media element the context menu was invoked on.inErrorboolean - Whether the media element has crashed.isPausedboolean - Whether the media element is paused.isMutedboolean - Whether the media element is muted.hasAudioboolean - Whether the media element has audio.isLoopingboolean - Whether the media element is looping.isControlsVisibleboolean - Whether the media element's controls are visible.canToggleControlsboolean - Whether the media element's controls are toggleable.canPrintboolean - Whether the media element can be printed.canSaveboolean - Whether or not the media element can be downloaded.canShowPictureInPictureboolean - Whether the media element can show picture-in-picture.isShowingPictureInPictureboolean - Whether the media element is currently showing picture-in-picture.canRotateboolean - Whether the media element can be rotated.canLoopboolean - Whether the media element can be looped.
editFlagsObject - These flags indicate whether the renderer believes it is able to perform the corresponding action.canUndoboolean - Whether the renderer believes it can undo.canRedoboolean - Whether the renderer believes it can redo.canCutboolean - Whether the renderer believes it can cut.canCopyboolean - Whether the renderer believes it can copy.canPasteboolean - Whether the renderer believes it can paste.canDeleteboolean - Whether the renderer believes it can delete.canSelectAllboolean - Whether the renderer believes it can select all.canEditRichlyboolean - Whether the renderer believes it can edit text richly.
Emitido cuando hay un nuevo menú de contexto que debe ser manejado.
Evento: 'select-bluetooth-device'
Devuelve:
eventdevicesBluetoothDevice[]callbackFunctiondeviceIdstring
Emitted when a bluetooth device needs to be selected when a call to navigator.bluetooth.requestDevice is made. callback should be called with the deviceId of the device to be selected. Passing an empty string to callback will cancel the request.
If 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.
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:
detailsEvent<>textureOffscreenSharedTexture (optional) Experimental - The GPU shared texture of the frame, whenwebPreferences.offscreen.useSharedTextureistrue.
dirtyRectRectangleimageNativeImage - The image data of the whole frame.
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.toBitmap())
})
win.loadURL('https://github.com')
When using shared texture (set webPreferences.offscreen.useSharedTexture to true) feature, you can pass the texture handle to external rendering pipeline without the overhead of copying data between CPU and GPU memory, with Chromium's hardware acceleration support. This feature is helpful for high-performance rendering scenarios.
Only a limited number of textures can exist at the same time, so it's important that you call texture.release() as soon as you're done with the texture. By managing the texture lifecycle by yourself, you can safely pass the texture.textureInfo to other processes through IPC.
More details can be found in the offscreen rendering tutorial. To learn about how to handle the texture in native code, refer to offscreen rendering's code documentation..
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ webPreferences: { offscreen: { useSharedTexture: true } } })
win.webContents.on('paint', async (e, dirty, image) => {
if (e.texture) {
// By managing lifecycle yourself, you can handle the event in async handler or pass the `e.texture.textureInfo`
// to other processes (not `e.texture`, the `e.texture.release` function is not passable through IPC).
await new Promise(resolve => setTimeout(resolve, 50))
// You can send the native texture handle to native code for importing into your rendering pipeline.
// Read more at https://github.com/electron/electron/blob/main/shell/browser/osr/README.md
// importTextureHandle(dirty, e.texture.textureInfo)
// You must call `e.texture.release()` as soon as possible, before the underlying frame pool is drained.
e.texture.release()
}
})
win.loadURL('https://github.com')
Evento: 'devtools-reload-page'
Emitido cuando la ventana devtools instruya la webContents para recargar
Evento: 'will-attach-webview'
Devuelve:
eventwebPreferencesWebPreferences - The web preferences that will be used by the guest page. This object can be modified to adjust the preferences for the guest page.paramsRecord<string, string> - The other<webview>parameters such as thesrcURL. 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:
eventwebContentsWebContents - 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:
detailsEvent<>messagestring - Message textlevelstring - Message severity Possible values includeinfo,warning,error, anddebug.lineNumberInteger - Line number in the log sourcesourceIdstring - URL of the log sourceframeWebFrameMain - Frame that logged the message
levelInteger Deprecated - The log level, from 0 to 3. In order it matchesverbose,info,warninganderror.messagestring Deprecated - The actual console messagelineInteger Deprecated - The line number of the source that triggered this console messagesourceIdstring Deprecated
Emitido cuando la ventana asociada registra un mensaje de consola.
Evento: 'error-preload'
Devuelve:
eventpreloadPathstringerrorError
Emitido cuando el script de preload preloadPathlanza una excepción no manejada error.
Evento: 'ipc-message'
Devuelve:
eventIpcMainEventchannelcadena...argsany[]
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:
eventIpcMainEventchannelcadena...argsany[]
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:
eventpreferredSizeSize - 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:
eventdetailsObjectframeWebFrameMain | null - The created frame. May benullif accessed after the frame has either navigated or been destroyed.
Emitted when the mainFrame, an <iframe>, or a nested <iframe> is loaded within the page.
Métodos de Instancia
contents.loadURL(url[, options])
urlstring
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])
filePathstring
Returns Promise<void> - the promise will resolve when the page has finished loading (see did-finish-load), and rejects if the page fails to load (see did-fail-load).
Loads the given file in the window, filePath should be a path to an HTML file relative to the root of your application. For instance an app structure like this:
| 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])
urlstring
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])
optsObject (optional)waitForBeforeUnloadboolean - if true, fire thebeforeunloadevent before closing the page. If the page prevents the unload, the WebContents will not be closed. Thewill-prevent-unloadwill 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() Obsoleto
History
| Version(s) | Changes |
|---|---|
None | API DEPRECATED |
Devuelve boolean - Si el navegador puede volver a la página web anterior.
Obsoleto: Debería usar la nueva API contents.navigationHistory.canGoBack.
contents.canGoForward() Obsoleto
History
| Version(s) | Changes |
|---|---|
None | API DEPRECATED |
Devuelve boolean - Si el navegador puede avanzar a la siguiente página web.
Obsoleto: Debería usar la nueva API contents.navigationHistory.canGoForward.
contents.canGoToOffset(offset) Obsoleto
History
| Version(s) | Changes |
|---|---|
None | API DEPRECATED |
offsetÍntegro
Devuelve boolean - Si la página web puede ir a offset.
Obsoleto: Debería usar la nueva API contents.navigationHistory.canGoToOffset.
contents.clearHistory() Obsoleto
History
| Version(s) | Changes |
|---|---|
None | API DEPRECATED |
Borra el historial de navegación.
Deprecated: Should use the new contents.navigationHistory.clear API.
contents.goBack() Obsoleto
History
| Version(s) | Changes |
|---|---|
None | API DEPRECATED |
Hace que el navegador regrese a una página web.
Deprecated: Should use the new contents.navigationHistory.goBack API.
contents.goForward() Obsoleto
History
| Version(s) | Changes |
|---|---|
None | API DEPRECATED |
Hace que el navegador avance a una página web.
Obsoleto: Debería usar la nueva API contents.navigationHistory.goForward.
contents.goToIndex(index) Obsoleto
History
| Version(s) | Changes |
|---|---|
None | API DEPRECATED |
indexÍntegro
Navega al índice de página web absoluta especificado.
Obsoleto: Debería usar la nueva API contents.navigationHistory.goToIndex.
contents.goToOffset(offset) Obsoleto
History
| Version(s) | Changes |
|---|---|
None | API DEPRECATED |
offsetÍntegro
Navega hacia el offset especificado desde "la entrada actual".
Obsoleto: Debería usar la nueva API contents.navigationHistory.goToOffset.
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)
userAgentcadena
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])
csscadena
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)
llavecadena
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])
codigostringuserGestureboolean (opcional) - Predeterminado esfalso.
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])
worldIdInteger - El ID de la palabra para correr javascript en,0es el mundo por defecto,999es el mundo usado por la característicacontextIsolationde Electron. Aquí puede suministrar cualquier entero.scriptsWebSource[]userGestureboolean (opcional) - Predeterminado esfalso.
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)
ignoreboolean
Ignora los accesos directos del menú de la aplicación mientras se enfoca los contenidos de la web.
contents.setWindowOpenHandler(handler)
-
handlerFunction<WindowOpenHandlerResponse>detailsObjecturlstring - La versión resuelta de la URL pasada awindow.open(). por ejemplo una ventana conwindow.open('foo')producirá algo comohttps://the-origin/the/current/path/foo.frameNamestring - Nombre de la ventana proporcionado enwindow.open()featuresstring - Lista separada por coma de la características de ventana proporcionada awindow.open().dispositionstring - Can bedefault,foreground-tab,background-tab,new-windoworother.referrerReferrer - The referrer that will be passed to the new window. Puede resultar o no en la cabeceraReferersiendo enviado, dependiendo de la política de referencia.postBodyPostBody (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 establecetarget=_blank.
Returns
WindowOpenHandlerResponse- When set to{ action: 'deny' }cancels the creation of the new window.{ action: 'allow' }permitirá la que se cree la nueva ventana. 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">. 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 })
return browserView.webContents
}
}
})
contents.setAudioMuted(muted)
mutedboolean
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)
factorDouble - 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)
nivelnú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)
minimumLevelnúmeromaximumLevelnú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)
xIntegeryInteger
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)
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:
After:
contents.replace(text)
textocadena
Ejecuta el comando de edición replace en la página web.
contents.replaceMisspelling(text)
textocadena
Ejecuta el comando de edición replaceMisspelling en página web.
contents.insertText(text)
textocadena
Devuelve Promise<void>
Inserta texto en el elemento enfocado.
contents.findInPage(text[, options])
textstring - El contenido para ser buscado, no debe quedar en blanco.
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. The result of the request can be obtained by subscribing to found-in-page event.
contents.stopFindInPage(action)
actionstring - Specifies the action to take place when endingwebContents.findInPagerequest.clearSelection- 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])
rectRectangle (optional) - The area of the page to be captured.optsObject (optional)stayHiddenboolean (opcional) - Mantiene la página oculta en lugar de visible. Por defecto esfalse.stayAwakeboolean (optional) - Keep the system awake instead of allowing it to sleep. Por defecto esfalse.
Returns Promise<NativeImage> - Resolves with a 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. It returns true when the capturer count is greater than 0.
contents.getPrintersAsync()
Obtiene la lista de impresora del sistema.
Returns Promise<PrinterInfo[]> - Resolves with a PrinterInfo[]
contents.print([options], [callback])
retrocallbackFuncion (opcional)successboolean - Indica el éxito de la llamada impresa.failureReasonstring - 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)
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)
pathstring
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)
pathstring
Elimina la ruta especificada del espacio de trabajo de DevTools.
contents.setDevToolsWebContents(devToolsWebContents)
devToolsWebContentsWebContents
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:
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])
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)
titlestring
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)
xIntegeryInteger
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)
channelcadena...argsany[]
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.
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)
frameIdInteger | [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.channelcadena...argsany[]
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.
The renderer process can handle the message by listening to channel with the ipcRenderer module.
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])
channelcadenamensajecualquieratransferMessagePortMain[] (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)
parametersObjectscreenPositionstring - Specify the screen type to emulate (default:desktop):desktop- El tipo de la pantalla de escritorio.mobile- El tipo de la pantalla móvil.
screenSizeSize - Set the emulated screen size (screenPosition == mobile).viewPositionPoint - Position the view on the screen (screenPosition == mobile) (default:{ x: 0, y: 0 }).deviceScaleFactorInteger - Configura el factor escala del dispositivo (si es cero regresa por defecto al factor de escala original del dispositivo) (por defecto:0).viewSizeSize - Set the emulated view size (empty means no override)scaleFloat - 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)
inputEventMouseInputEvent | MouseWheelInputEvent | KeyboardInputEvent
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)
onlyDirtyboolean (opcional) - Por defecto esfalse.callbackFunctionimageNativeImagedirtyRectRectangle
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
itemfilestring - La ruta al archivo que está siendo arrastrado.filesstring[] (opcional) - Las rutas a los archivos que están siendo arrastrados. (filesanulará el campofile)iconNativeImage | 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)
fullPathstring - The absolute file path.saveTypestring - 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)
fpsInteger
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)
policystring - 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:
minInteger - The minimum UDP port number that WebRTC should use.maxInteger - 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)
udpPortRangeObjectminInteger - The minimum UDP port number that WebRTC should use.maxInteger - 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)
requestWebContentsWebContents - 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)
filePathstring - 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)
History
allowedboolean
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)
policystring - Puede seranimate,animateOnceonoAnimation.
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:
contents.on('ipc-message')contents.mainFrame.on(channel)contents.ipc.on(channel)ipcMain.on(channel)
Handlers registered with invoke will be checked in the following order. The first one that is defined will be called, the rest will be ignored.
contents.mainFrame.handle(channel)contents.handle(channel)ipcMain.handle(channel)
A handler or event listener registered on the WebContents will receive IPC messages sent from any frame, including child frames. In most cases, only the main frame can send IPC messages. However, if the nodeIntegrationInSubFrames option is enabled, it is possible for child frames to send IPC messages also. In that case, handlers should check the senderFrame property of the IPC event to ensure that the message is coming from the expected frame. Alternatively, register handlers on the appropriate frame directly using the WebFrameMain.ipc interface.
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
A Session used by this webContents.
contents.navigationHistory SoloLectura
Un NavigationHistory usado por este webContents.
contents.hostWebContents Readonly
A WebContents instance that might own this 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
A Debugger instance for this webContents.
contents.backgroundThrottling
History
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 | null property that represents the frame that opened this WebContents, either with open(), or by navigating a link with a target attribute.
contents.focusedFrame SoloLectura
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.