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('http://github.com')
const contents = win.webContents
console.log(contents)
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()
Devuelve WebContents
| null - El contenido web que está enfocado en esta aplicación, de lo contrario devuelve null
.
webContents.fromId(id)
id
Íntegro
Devuelve WebContents
| undefined - Una instancia de WebContents con el ID dado, o undefined
si no hay WebContents asociados con ID dado.
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.
Devuelve WebContents
| undefined - Una instancia de WebContents con el TargetID, o undefined
si no hay WebContents asociados con el TargetID dado.
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 webContents.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
IntegererrorDescription
stringvalidatedURL
stringisMainFrame
booleanframeProcessId
IntegerframeRoutingId
Integer
Este evento es como did-finish-load
pero emitido cuando falló la carga. La lista completa de los códigos de error y su significado está disponible aquí.
Evento: 'did-fail-provisional-load'
Devuelve:
event
errorCode
IntegererrorDescription
stringvalidatedURL
stringisMainFrame
booleanframeProcessId
IntegerframeRoutingId
Integer
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
booleanframeProcessId
IntegerframeRoutingId
Integer
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
stringexplicitSet
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 Windowsdetails
Objecturl
string - URL de la ventana creada.frameName
string - Nombre dado a la ventana creada en la llamadawindow.open()
.referrer
Referrer - El remitente que será pasado a la nueva ventana. Puede resultar o no en la cabeceraReferer
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 settarget=_blank
.disposition
string - Can bedefault
,foreground-tab
,background-tab
,new-window
,save-to-disk
andother
.
Emitted after successful creation of a window via window.open
in the renderer. No emitido si la creación de la ventana es cancelada desde webContents.setWindowOpenHandler
.
See window.open()
for more details and how to use this in conjunction with webContents.setWindowOpenHandler
.
Evento: 'will-navigate'
Devuelve:
event
url
string
Emitido cuando un usuario o l página quiere empezar la navegación. 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.
Evento: 'did-start-navigation'
Devuelve:
event
url
stringisInPlace
booleanisMainFrame
booleanframeProcessId
IntegerframeRoutingId
Integer
Emitido cuando cualquier frame (incluyendo el principal) comienza la navegación. isInPlace
will be true
for in-page navigations.
Evento: 'will-redirect'
Devuelve:
event
url
stringisInPlace
booleanisMainFrame
booleanframeProcessId
IntegerframeRoutingId
Integer
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:
event
url
stringisInPlace
booleanisMainFrame
booleanframeProcessId
IntegerframeRoutingId
Integer
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
stringhttpResponseCode
Integer - -1 para navegaciones no HTTPhttpStatusText
string - vacío para navegaciones no HTTP
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
stringhttpResponseCode
Integer - -1 para navegaciones no HTTPhttpStatusText
string - vacío para navegaciones no HTTP,isMainFrame
booleanframeProcessId
IntegerframeRoutingId
Integer
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
stringisMainFrame
booleanframeProcessId
IntegerframeRoutingId
Integer
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: 'crashed' Obsoleto
Devuelve:
event
killed
boolean
Emitido cuando el proceso se crashea o es terminado.
Obsoleto: Este evento es reemplazado por el evento render-process-gone
el cual contiene más información acerca de porque desapareció el renderer process. No siempre se debe a que haya dejado de funcionar. El booleano killed
puede ser reemplazado al comprobar que reason === 'killed'
cuando se cambie a ese evento.
Evento: 'render-process-gone'
Devuelve:
event
details
Objectreason
string - The reason the render process is gone. Posibles valores:clean-exit
-El proceso ha finalizado con un exit code de ceroabnormal-exit
- El proceso a finalizado con un exit code distinto de cerokilled
- El proceso a enviado un SIGTERM o se a finalizado externamentecrashed
- El proceso crasheooom
- El proceso se quedo sin memorialaunch-failed
- El proceso nunca se ha ejecutado correctamenteintegrity-failure
- las verificaciones de integridad de código de Windows fallaron
exitCode
Integer - El código de salida del proceso, a menos quereason
sealaunch-failed
, en cuyo casoexitCode
será un código de error de ejecución especifico de la plataforma.
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
stringversion
cadena
Emitido cuando el proceso de enchufe se ha caído.
Evento: 'destroyed'
Emitido cuando webContents
es destruido.
Event: 'input-event'
Devuelve:
event
inputEvent
InputEvent
Emitted when an input event is sent to the WebContents. See InputEvent for details.
Evento: 'before-input-event'
Devuelve:
event
input
Object - Input properties.type
string - SeakeyUp
okeyDown
.key
string - Es igual a KeyboardEvent.key.code
string - Es igual a KeyboardEvent.code.isAutoRepeat
boolean - Es igual a KeyboardEvent.repeat.isComposing
boolean - Equivalente a KeyboardEvent.isComposing.shift
boolean - Es igual a KeyboardEvent.shiftKey.control
boolean - Es igual a KeyboardEvent.controlKey.alt
boolean - Es igual a KeyboardEvent.altKey.meta
boolean - Es igual a KeyboardEvent.metaKey.location
number - Equivalente a KeyboardEvent.location.modifiers
string[] - Ver 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ú.
Para evitar sólo los accesos directos del menú, 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 - Puede serin
oout
.
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.
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: 'certificate-error'
Devuelve:
event
url
stringerror
string - El código de error.certificate
certificatecallback
FunciónisTrusted
boolean - indica si el certificado se puede considerar de confianza.
isMainFrame
boolean
Emitido cuando no se pudo verificar el certificate
for url
.
El uso es el mismo con the certificate-error
evento de app
.
Evento: 'select-client-certificate'
Devuelve:
event
url
URLcertificateList
Certificate[]callback
Funcióncertificate
Certificate - Debe ser un certificado de la lista dada.
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
Objecturl
URL
authInfo
ObjectisProxy
booleanscheme
stringhost
stringpuerto
Íntegrorealm
string
callback
Funciónusername
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
ÍntegroactiveMatchOrdinal
Integer - Posición de la coincidencia activa.matches
Integer - Número de coincidencias.selectionArea
Rectangle - Coordenadas de la primera región de coincidencia.finalUpdate
boolean
Emitido cuando un resultado está disponible para la petición de [webContents.findInPage
].
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.
Evento: 'did-change-theme-color'
Devuelve:
event
color
(string | null) - Theme color is in format of '#rrggbb'. It isnull
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
stringimage
NativeImage (opcional)scale
Float (opcional) - Factor de escala para el cursor personalizado.size
Size (opcional) - El tamaño de laimage
.hotspot
Point (opcional) - Coordenadas de la zona activa del cursor personalizado.
Emitido cuando el tipo del cursor cambia. El parámetro type
puede ser default
, crosshair
, pointer
, 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
, 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
or custom
.
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
- Objeto
params
- Entero
x
- coordenadas x. - Entero
y
- coordenadas x. frame
WebFrameMain - Frame desde el cual se invocó el menú contextual.linkURL
string - URL del enlace que incluye el nodo del menú contextual que fue invocado.linkText
string - Text associated with the link. May be an empty string if the contents of the link are an image.pageURL
string - URL de la parte superior del nivel de la página que se invocó en el menú del contexto.framseURL
string - URL de la parte inferior del marco que se invocó en el menú del contexto.srcURL
string - Source URL for the element that the context menu was invoked on. Elements with source URLs are images, audio and video.mediaTipo
string - Tipo de nodo que el menú del contexto fue invocado. Puede sernone
,image
,audio
,video
,canvas
,file
oplugin
.<0>tieneImagenContenido
boolean - si el menú del contexto fue invocado en una imagen la cual tiene contenido no vacío.esEditable
boolean - Si el contexto es editable.selectrionText
string. Texto de la selección la cual el menú del contexto fue invocado.titleText
string - Ttexto del título de la selección en la que se invocó el menú contextual.altText
string - Texto alternativo de la selección en la que se invocó el menú contextual.suggestedFilename
string - Nombre de archivo sugerido para ser usado cuando se guarde el archivo a través de la opción 'Guarde Enlace Como' del menú contextual.selectionRect
Rectángulo - Rectángulo que representa las coordenadas en el espacio del documento de la selección.SelectionStartOffset
number - Posición inicial del texto de selección.referrerPolicy
Referrer - La política de referencia del frame en el cual el menú es invocado.misspelledWord
string - La palabra mal escrita bajo el cursor, si cualquiera.dictionarySuggestions
string[] - Un array de palabras sugeridas para mostrar al usuario para remplazar elmisspelledWord
. Solo disponible si hay una palabra mal escrita y el corrector está habilitado.frameCharset
string - La codificación de carácteres de la estructura la cual el menú fue invocado.inputFieldType
cadena - Si se invoca el menú de contexto en un campo de entrada, el tipo de ese campo. Los valores posibles sonnone
,plainText
,password
,other
.spellcheckEnabled
boolean - Si el contexto es editable, si el corrector ortográfico está habilitado o no.menuSourceType
string - Input source that invoked the context menu. Puede sernone
,mouse
,keyboard
,touch
,touchMenu
,longPress
,longTap
,touchHandle
,stylus
,adjustSelection
, oadjustSelectionReset
.mediaFlags
Object - The flags for the media element the context menu was invoked on.enError
boolean - Si el elemento multimedia se ha dañado.estáPausado
boolean - Si el elemento multimedia está pausado.estáSilenciado
boolean - Si el elemento multimedia está silenciado.tieneAudio
boolean - Si el elemento multimedia tiene audio.estáLooping
boolean - Si el elemento multimedia está enredado.esControlVisible
boolean - Si los controles del elemento multimedia son visibles.puedeToggleControles
boolean - Si los controles de los elementos multimedia son toggleable.canPrint
boolean - Si el elemento multimedia puede ser impreso.canSave
boolean - Si el elemento multimedia puede ser descargado o no.canShowPictureInPicture
boolean - Si el elemento multimedia puede ser mostrado en picture-in-picture.isShowingPictureInPicture
boolean - Si el elemento multimedia está siendo actualmente mostrado en picture-in-picture.puedeRotar
boolean - Si el elemento multimedia puede ser rotado.canLoop
boolean - Si el elemento multimedia puede hacer un loop.
editFlags
Object - These flags indicate whether the renderer believes it is able to perform the corresponding action.canUndo
boolean - Si cree que el procesador puede deshacer.canRedo
boolean - Si cree que el procesador pueda rehacer.canCut
boolean - Si cree que el procesador puede cortar.canCopy
boolean - Si cree que el procesador puede copiar.canPaste
boolean - Si cree que el procesador puede pegar.canDelete
boolean - Si cree que el procesador puede borrar.canSelectAll
boolean - Si cree que el procesador puede seleccionar todo.canEditRichly
boolean - Si el renderer cree que puede editar texto de forma enriquecedora.
- Entero
Emitido cuando hay un nuevo menú de contexto que debe ser manejado.
Evento: 'select-bluetooth-device'
Devuelve:
event
devices
BluetoothDevice[]callback
FuncióndeviceId
string
Emite cuando el dispositivo bluetooth necesita ser seleccionado en la llamada navigator.bluetooth.requestDevice
. Para usar navigator.bluetooth
api webBluetooth
debe ser activada. Si no se llama event.preventDefault
el primer dispositivo disponible será seleccionado. callback
puede ser llamado con deviceId
ser seleccionado,.
If no event listener is added for this event, all bluetooth requests will be cancelled.
const { app, BrowserWindow } = require('electron')
let win = null
app.commandLine.appendSwitch('enable-experimental-web-platform-features')
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) {
callback('')
} else {
callback(result.deviceId)
}
})
})
Evento: 'paint'
Devuelve:
event
dirtyRect
Rectangleimage
NativeImage - La información de la imagen de todo el fotograma.
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('http://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 thesrc
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 matchesverbose
,info
,warning
anderror
.message
string - The actual console messageline
Entero - El número de línea de la fuente que activó este mensaje de consolasourceId
cadena
Emitido cuando la ventana asociada registra un mensaje de consola.
Evento: 'error-preload'
Devuelve:
event
preloadPath
stringerror
Error
Emitido cuando el script de preload preloadPath
lanza una excepción no manejada error
.
Evento: 'ipc-message'
Devuelve:
event
channel
cadena...args
any[]
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:
event
channel
cadena...args
any[]
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
Objectframe
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
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 { webContents } = require('electron')
const options = { extraHeaders: 'pragma: no-cache\n' }
webContents.loadURL('https://github.com', options)
contents.loadFile(filePath[, options])
filePath
string
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
win.loadFile('src/index.html')
contents.downloadURL(url)
url
string
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('http://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 thebeforeunload
event before closing the page. If the page prevents the unload, the WebContents will not be closed. Thewill-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()
Returns boolean
- Whether the web page is waiting for a first-response from the main resource of the page.
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()
Returns boolean
- Whether the browser can go back to previous web page.
contents.canGoForward()
Returns boolean
- Whether the browser can go forward to next web page.
contents.canGoToOffset(offset)
offset
Íntegro
Returns boolean
- Whether the web page can go to 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
.
contents.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) {
contents.forcefullyCrashRenderer()
contents.reload()
}
})
contents.setUserAgent(userAgent)
userAgent
cadena
Anula el agente usuario para esta página web.
contents.getUserAgent()
Returns string
- The user agent for this web page.
contents.insertCSS(css[, options])
css
cadena
Returns Promise<string>
- A promise that resolves with a key for the inserted CSS that can later be used to remove the CSS via contents.removeInsertedCSS(key)
.
Inyecta CSS en la página web actual y devuelve un identificador único para la hoja de estilo insertada.
contents.on('did-finish-load', () => {
contents.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)
.
contents.on('did-finish-load', async () => {
const key = await contents.insertCSS('html, body { background-color: #f00; }')
contents.removeInsertedCSS(key)
})
contents.executeJavaScript(code[, userGesture])
codigo
stringuserGesture
boolean (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.
contents.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ísticacontextIsolation
de Electron. Aquí puede suministrar cualquier entero.scripts
WebSource[]userGesture
boolean (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)
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
Objecturl
string - The resolved version of the URL passed towindow.open()
. por ejemplo una ventana conwindow.open('foo')
producirá algo comohttps://the-origin/the/current/path/foo
.frameName
string - Name of the window provided inwindow.open()
features
string - Comma separated list of window features provided towindow.open()
.disposition
string - Can bedefault
,foreground-tab
,background-tab
,new-window
,save-to-disk
orother
.referrer
Referrer - El remitente que será pasado a la nueva ventana. Puede resultar o no en la cabeceraReferer
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
. Solo se define cuando la ventana está siendo creada por un formulario que establecetarget=_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. EspecificandooverrideBrowserWindowOptions
permite la personalización de la ventana creada. By default, child windows are closed when their opener is closed. This can be changed by specifyingoutlivesOpener: 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">
. See window.open()
for more details and how to use this in conjunction with did-create-window
.
contents.setAudioMuted(muted)
muted
boolean
Silencia el audio la página web actual.
contents.isAudioMuted()
Returns boolean
- Whether this page has been muted.
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úmeromaximumLevel
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:
contents.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.copyImageAt(x, y)
x
Integery
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.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.
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)
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 { webContents } = require('electron')
webContents.on('found-in-page', (event, result) => {
if (result.finalUpdate) webContents.stopFindInPage('clearSelection')
})
const requestId = webContents.findInPage('api')
console.log(requestId)
contents.capturePage([rect])
rect
Rectangle (opcional) - El área de la página para ser capturada.
Devuelve Promise<NativeImage>
- Resuelve con el un NativeImage
Captura una foto instantánea de la página dentro de rect
. Omitiendo rect
capturará toda la página visible.
contents.isBeingCaptured()
Devuelve boolean
- Si esta página está siendo capturada. Devuelve true cuando el recuento de capturadores es mas grande que 0.
contents.incrementCapturerCount([size, stayHidden, stayAwake])
size
Tamaño (opcional) - El tamaño preferido para el capturador.stayHidden
boolean (opcional) - Mantiene la página oculta en lugar de visible.stayAwake
boolean (optional) - Keep the system awake instead of allowing it to sleep.
Incrementa el contador de captura en uno. La página es considerada visible cuando su ventana de navegador está oculta y el recuento del capturador no es cero. Si le gustaría que la página permanezca oculta, debería asegurarse que stayHidden
está establecido a true.
Esto también afecta a la API de visibilidad de la página.
contents.decrementCapturerCount([stayHidden, stayAwake])
stayHidden
boolean (opcional) - Mantiene la página en estado oculto en lugar de visible.stayAwake
boolean (optional) - Keep the system awake instead of allowing it to sleep.
Disminuye el recuento del capturador en uno. La página se establecerá en el estado oculto u ocluido cuando la ventana del navegador esté oculta u ocluida y el recuento del capturador llegue a cero. Si quiere disminuir el contador del caputador en su lugar debería establecer stayHidden
a true.
contents.getPrinters()
Obsoleto
Obtiene la lista de impresora del sistema.
Devuelve PrinterInfo[]
Deprecated: Use la nueva API de contents.getPrintersAsync
.
contents.getPrintersAsync()
Obtiene la lista de impresora del sistema.
Devuelve Promise<PrinterInfo[]>
- Resuelve con un PrinterInfo[]
contents.print([options], [callback])
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 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 { BrowserWindow } = require('electron')
const fs = require('fs')
const path = require('path')
const os = require('os')
const win = new BrowserWindow()
win.loadURL('http://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
:
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()
Returns boolean
- Whether the devtools is opened.
contents.isDevToolsFocused()
Returns boolean
- Whether the devtools view is focused .
contents.toggleDevTools()
Alterna las herramientas de desarrollador.
contents.inspectElement(x, y)
x
Integery
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)
workerId
string
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.
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
.
Un ejemplo de envío de mensajes desde el proceso principal al proceso de renderizado:
/// In the main process.
const { app, BrowserWindow } = require('electron')
let win = null
app.whenReady().then(() => {
win = new BrowserWindow({ width: 800, height: 600 })
win.loadURL(`file://${__dirname}/index.html`)
win.webContents.on('did-finish-load', () => {
win.webContents.send('ping', 'whoooooooh!')
})
})
<!-- index.html -->
<html>
<body>
<script>
require('electron').ipcRenderer.on('ping', (event, message) => {
console.log(message) // Prints 'whoooooooh!'
})
</script>
</body>
</html>
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
cadenamensaje
cualquieratransfer
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 { port1, port2 } = new MessageChannelMain()
webContents.postMessage('port', { message: 'hello' }, [port1])
// Renderer process
ipcRenderer.on('port', (e, msg) => {
const [port] = e.ports
// ...
})
contents.enableDeviceEmulation(parameters)
parameters
ObjectscreenPosition
string - Specify the screen type to emulate (default:desktop
):desktop
- Desktop screen type.mobile
- Mobile screen type.
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 - Set the device scale factor (if zero defaults to original device scale factor) (default:0
).viewSize
Size - Set the emulated view size (empty means no override)scale
Float - Scale of emulated view inside available space (not in fit to view mode) (default: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)
inputEvent
MouseInputEvent | 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)
onlyDirty
boolean (optional) - Defaults tofalse
.callback
Funciónimage
NativeImagedirtyRect
Rectangle
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)
item
Objectfile
string - The path to the file being dragged.files
string[] (optional) - The paths to the files being dragged. (files
anulará el campofile
)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()
Returns boolean
- Indicates whether offscreen rendering is enabled.
contents.startPainting()
If offscreen rendering is enabled and not painting, start painting.
contents.stopPainting()
If offscreen rendering is enabled and painting, stop painting.
contents.isPainting()
Returns boolean
- If offscreen rendering is enabled returns whether it is currently painting.
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()
Returns Integer
- If offscreen rendering is enabled returns the current frame rate.
contents.invalidate()
Programa un repintado completo de la ventana en la que se encuentra este contenido web.
If offscreen rendering is enabled invalidates the frame and generates a new one through the 'paint'
event.
contents.getWebRTCIPHandlingPolicy()
Returns string
- Returns the 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.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()
Returns boolean
- whether or not this WebContents will throttle animations and timers when the page becomes backgrounded. 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 seranimate
,animateOnce
onoAnimation
.
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.
Solo aplicable si offscreen rendering está habilitado.
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.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.