Saltar al contenido principal

<webview> Etiqueta

Advertencia

La etiqueta webview de Electron está basada en Chromium's webview, el cual está experimentado cambios de arquitectura dramáticos. Esto impacta la estabilidad de webviews, incluyendo el renderizado, navegación y el enrutamiento de evento. We currently recommend to not use the webview tag and to consider alternatives, like iframe, a WebContentsView, or an architecture that avoids embedded content altogether.

Activando

By default the webview tag is disabled in Electron >= 5. Usted necesita habilitar la etiqueta estableciendo la opción webviewTag de webPreferences cuando se construye su BrowserWindow. Para más información vea el BrowserWindow constructor docs.

Descripción general

Mostrar contenido externo de la web en un cuadro aislado y procesado.

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

Use the webview tag to embed 'guest' content (such as web pages) in your Electron app. The guest content is contained within the webview container. Una página incrustada dentro de los controles de tu aplicación como el contenido de invitado es dispuesto y renderizado.

Unlike an iframe, the webview runs in a separate process than your app. It doesn't have the same permissions as your web page and all interactions between your app and embedded content will be asynchronous. Esto mantiene a tu aplicación a salvo del contenido incrustado. Note: Muchos de los métodos en la vista web de la página anfitriona requieren una llamada sincrónica al proceso principal.

Ejemplo

Para incrustar una página web en tu aplicación, añade la etiqueta webview a la página de embebido de tu aplicación (esta es la página de la aplicación que mostrará el contenido del invitado). En su manera más sencilla, la etiqueta webview incluye el src de la página web y los estilos css que controlan la apariencia de el contenedor webview:

<webview id="foo" src="https://www.github.com/" style="display:inline-flex; width:640px; height:480px"></webview>

Si tú quieres controlar el contenido de invitado de cualquier manera, puedes escribir JavaScript que escucha los eventos webview y responde a esos eventos usando los métodos webview. Aquí tenemos un código de muestra con dos detectores de eventos: uno que escucha para que la página web empiece a cargar, la otra para que la página web deje de cargar y muestre un mensaje que indique "cargando..." durante el tiempo de carga:

<script>
onload = () => {
const webview = document.querySelector('webview')
const indicator = document.querySelector('.indicator')

const loadstart = () => {
indicator.innerText = 'loading...'
}

const loadstop = () => {
indicator.innerText = ''
}

webview.addEventListener('did-start-loading', loadstart)
webview.addEventListener('did-stop-loading', loadstop)
}
</script>

Implementación interna

Bajo la capa webview es implementado con Out-of-Process iframes (OOPIFs). La etiqueta webview es esencialmente un elemento personalizado usando shadow DOM para envolver un elemento iframe dentro de el.

Entonces el comportamiento de webview es muy similar a iframe cross-domain, como ejemplos:

  • Cuando se pulsa dentro de un webview, el foco de la página se moverá desde el incrustador a webview.
  • Usted puede no agregar escuchadores de eventos de teclado, mouse y scroll a webview.
  • Todas las reacciones entre el frame embebedor y el webview son asíncronas.

Notas de Estilo CSS

Por favor tenga en cuenta que las etiquetas de estilos de webview usa internamente display:flex; para asegurar que el elemento iframe hijo rellena el alto y el ancho por completo de su webview contenedor cuando es usado con el layouts tradicionales y flexbox. Por favor no sobrescrita la propiedad CSS por defecto display:flex; a menos que se especifique display:inline-flex; para layout inline.

Atributos de Etiqueta

La etiqueta de webview tiene los siguientes atributos:

src

<webview src="https://www.github.com/"></webview>

A string representing the visible URL. Writing to this attribute initiates top-level navigation.

Asignarle a src su propio valor reiniciará la página actual.

El atributo src puede aceptar data de URL, como data:text/plain,Hello, world!.

nodeintegration

<webview src="https://www.google.com/" nodeintegration></webview>

Un boolean. Cuando este atributo esté presente, la página de invitado en webview tendrá integración de nodo y puede usar nodos APIs como require y process para acceder a bajos niveles de recursos de sistemas. La integración de nodo está desactivada por defecto en la página de invitado.

nodeintegrationinsubframes

<webview src="https://www.google.com/" nodeintegrationinsubframes></webview>

Un boolean para habilitar la opción experimental soporte NodeJS en sub frames tal como iframes dentro de webview. Todas sus precargas se cargarán por cada iframe, pude usar process.isMainFrame para determinar si estás en el frame principal o no. Esta opción está deshailitada por defecto en la pagina de invitado.

plugins

<webview src="https://www.github.com/" plugins></webview>

Un boolean. When this attribute is present the guest page in webview will be able to use browser plugins. Plugins are disabled by default.

preload

<!-- desde un archivo -->
<webview src="https://www.github.com/" preload="./test.js"></webview>
<!-- o si quiere cargar desde un archivo asar -->
<webview src="https://www.github.com/" preload="./app.asar/test.js"></webview>

Un string que especifica un script que será cargada antes que se ejecuten otros scripts en la página de invitado. El protocolo URL del script debe ser file: (incluso cuando usa archivos asar:) porque bajo el capo será cargado por el require de Node, el cual trata los archivos asar: como directorios virtuales.

Cuando la página de invitado no tiene integración de nodo, este guión todavía tendrá acceso a todos los nodos APIs, pero los objetos globales inyectados por Nodo serán eliminados luego de que el guión haya finalizado de ejecutarse.

httpreferrer

<webview src="https://www.github.com/" httpreferrer="https://example.com/"></webview>

Un string que establece la URL de referencia para la página de invitado.

useragent

<webview src="https://www.github.com/" useragent="Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko"></webview>

A string that sets the user agent for the guest page before the page is navigated to. Once the page is loaded, use the setUserAgent method to change the user agent.

disablewebsecurity

<webview src="https://www.github.com/" disablewebsecurity></webview>

Un boolean. When this attribute is present the guest page will have web security disabled. Web security is enabled by default.

This value can only be modified before the first navigation.

partition

<webview src="https://github.com" partition="persist:github"></webview>
<webview src="https://electronjs.org" partition="electron"></webview>

Un string que representa la sesión utilizada por la página. Si partition empieza con persist:, la página usará una sesión persistente disponible para todas las páginas en la aplicación con la misma partition. si no hay un prefijo persist:, la página usará una sesión en memoria. Al asignar la misma partition, las páginas múltiples pueden compartir la misma sesión. Si la partition no se establece entonces la sesión por defecto de la aplicación será usada.

This value can only be modified before the first navigation, since the session of an active renderer process cannot change. Subsequent attempts to modify the value will fail with a DOM exception.

allowpopups

<webview src="https://www.github.com/" allowpopups></webview>

Un boolean. When this attribute is present the guest page will be allowed to open new windows. Popups are disabled by default.

webpreferences

<webview src="https://github.com" webpreferences="allowRunningInsecureContent, javascript=no"></webview>

Un string el cual es una lista de cadenas separada por coma que especifica las web preferences a ser establecidas en el webview. La lista completa de cuerdas preferenciales soportadas puede ser encontradas en BrowserWindow. In addition, webview supports the following preferences:

  • transparent boolean (optional) - Whether to enable background transparency for the guest page. Por defecto es true. Note: The guest page's text and background colors are derived from the color scheme of its root element. When transparency is enabled, the text color will still change accordingly but the background will remain transparent.

La cuerda sigue el mismo formato que las cuerdas que aparecen en window.open. Un nombre por sí mismo es dado a true por valores booleanos. Una preferencia puede ser establecida por otro valor incluyendo un =, seguido por el valor. Valores especiales como yes y 1 son interpretados como true, mientras que no y 0 son interpretados como false.

enableblinkfeatures

<webview src="https://www.github.com/" enableblinkfeatures="PreciseMemoryInfo, CSSVariables"></webview>

Un string que es una lista de cadenas que especifica las funciones de parpadeo que se habilitarán separadas por ,. La lista completa de cadenas características soportadas puede ser encontrada en el archivo RuntimeEnabledFeatures.json5.

disableblinkfeatures

<webview src="https://www.github.com/" disableblinkfeatures="PreciseMemoryInfo, CSSVariables"></webview>

Un string que es una lista de cadenas que especifica las funciones de parpadeo a ser desactivadas separadas por ,. La lista completa de cadenas características soportadas puede ser encontrada en el archivo RuntimeEnabledFeatures.json5.

Métodos

La etiqueta de webview tiene los siguientes métodos:

Nota: El elemento webview debe ser cargado antes de usar los métodos.

Ejemplo

const webview = document.querySelector('webview')
webview.addEventListener('dom-ready', () => {
webview.openDevTools()
})

<webview>.loadURL(url[, options])

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

Devuelve Promise<void> - La promesa se resolverá cuando la pagina ha finalizado de cargar (ver did-finish-load), y rechaza si la página falla al cargar (ver did-fail-load).

Carga el url en el webview, el url debe contener el prefijo protocolo, e.g. el http:// or file://.

<webview>.downloadURL(url[, options])

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

Inicia una descarga del recurso en url sin navegar.

<webview>.getURL()

Devuelve string - El URL de la página de invitado.

<webview>.getTitle()

Returns string - The title of guest page.

<webview>.isLoading()

Devuelve boolean - Aunque la página de invitado esté cargando recursos.

<webview>.isLoadingMainFrame()

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

<webview>.isWaitingForResponse()

Devuelve boolean - Aunque la página de invitado esté esperando por una primera respuesta de el principal recurso de la página.

<webview>.stop()

Detiene cualquier navegación pendiente.

<webview>.reload()

Recarga la página de invitado.

<webview>.reloadIgnoringCache()

Recarga la página de invitado e ignora el caché.

<webview>.canGoBack()

Devuelve boolean - Aunque la página de invitado pueda retroceder.

<webview>.canGoForward()

Devuelve boolean - Aunque la página de invitado úeda ir hacia adelante.

<webview>.canGoToOffset(offset)

  • offset Íntegro

Devuelve boolean - Aunque la página de invitado pueda ir a offset.

<webview>.clearHistory()

Borra el historial de navegación.

<webview>.goBack()

Hace que la página de invitado vaya hacia atrás.

<webview>.goForward()

Hace que la página de invitado vaya hacia adelante.

<webview>.goToIndex(index)

  • index Íntegro

Navega a el índice absoluto específico.

<webview>.goToOffset(offset)

  • offset Íntegro

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

<webview>.isCrashed()

Devuelve boolean - Si el proceso de renderizado ha fallado.

<webview>.setUserAgent(userAgent)

  • userAgent cadena

Anula el agente usuario para la página de invitado.

<webview>.getUserAgent()

Devuelve string - El agente usuario para la página de invitado.

<webview>.insertCSS(css)

  • css cadena

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 <webview>contents.removeInsertedCSS(key).

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

<webview>.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 <webview>.insertCSS(css).

<webview>.executeJavaScript(code[, userGesture])

  • codigo string
  • userGesture boolean (opcional) - Predeterminado false.

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. Si userGesture está establecido, creará el contexto de gesto del usuario en la página. APIs de HTML como requestFullScreen, los cuales requieren acciones de usuario, puede tomar ventaja de esta opción para automatización.

<webview>.openDevTools()

Abre una ventana de DevTools para la página de invitado.

<webview>.closeDevTools()

Cierra la ventana de DevTools para la página de invitado.

<webview>.isDevToolsOpened()

Devuelve boolean - Aunque la página de invitado tenga una ventana de DevTools unida.

<webview>.isDevToolsFocused()

Devuelve boolean - Aunque la ventana de DevTools de la página de invitado esté centrada.

<webview>.inspectElement(x, y)

  • x Integer
  • y Integer

Empieza inspeccionado elementos en posición (x, y) de la página de invitado.

<webview>.inspectSharedWorker()

Abre el DevTools para el contexto de trabajadores compartidos presentes en la página de invitado.

<webview>.inspectServiceWorker()

Abre el DevTools para el contexto del trabajador de servicio presente en la página de invitado.

<webview>.setAudioMuted(muted)

  • muted boolean

Establece la página de invitado silenciada.

<webview>.isAudioMuted()

Devuelve boolean - Aunque a página de invitado haya sido silenciada.

<webview>.isCurrentlyAudible()

Devuelve boolean - Si el audio se esta reproduciendo actualmente.

<webview>.undo()

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

<webview>.redo()

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

<webview>.cut()

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

<webview>.copy()

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

<webview>.centerSelection()

Centers the current text selection in page.

<webview>.paste()

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

<webview>.pasteAndMatchStyle()

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

<webview>.delete()

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

<webview>.selectAll()

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

<webview>.unselect()

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

<webview>.scrollToTop()

Scrolls to the top of the current <webview>.

<webview>.scrollToBottom()

Scrolls to the bottom of the current <webview>.

<webview>.adjustSelection(options)

  • options Object
    • start Number (optional) - Amount to shift the start index of the current selection.
    • end Number (optional) - Amount to shift the end index of the current selection.

Adjusts the current text selection starting and ending points in the focused frame by the given amounts. A negative amount moves the selection towards the beginning of the document, and a positive amount moves the selection towards the end of the document.

See webContents.adjustSelection for examples.

<webview>.replace(text)

  • texto cadena

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

<webview>.replaceMisspelling(text)

  • texto cadena

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

<webview>.insertText(text)

  • texto cadena

Devuelve Promise<void>

Inserta texto en el elemento enfocado.

<webview>.findInPage(text[, options])

  • text string - El contenido para ser buscado, no debe quedar en blanco.
  • options Object (opcional)
    • forward boolean (opcional) - Ya sea para buscar hacia adelante o hacia atrás, el valor predeterminado es true.
    • findNext boolean (optional) - Whether to begin a new text finding session with this request. Should be true for initial requests, and false for follow-up requests. Por defecto es false.
    • matchCase boolean (opcional) - Si la busqueda debe ser sensible a mayúsculas, por defecto es false.

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

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

<webview>.stopFindInPage(action)

  • action string - Specifies the action to take place when ending <webview>.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 webview con la action dada.

<webview>.print([options])

  • options Object (opcional)
    • silent boolean (optional) - Don't ask user for print settings. Por defecto es false.
    • printBackground boolean (optional) - Prints the background color and image of the web page. Por defecto es false.
    • deviceName string (optional) - Set the printer device name to use. Must be the system-defined name and not the 'friendly' name, e.g 'Brother_QL_820NWB' and not 'Brother QL-820NWB'.
    • color boolean (optional) - Set whether the printed web page will be in color or grayscale. Por defecto es true.
    • margins Object (opcional)
      • marginType string (opcional) - Puede ser default, none, printableArea, o custom. Si custom es elegido, además necesitar especificar top, bottom, left, y right.
      • top number (opcional) - El margen superior de la página web impresa, en píxeles.
      • bottom number (opcional) - El margen inferior de la página web impresa, en píxeles.
      • left number (opcional) - El margen izquierdo de la página web impresa, en píxeles.
      • right number (opcional) - El margen derecho de la página web impresa, en píxeles.
    • landscape boolean (optional) - Whether the web page should be printed in landscape mode. Por defecto es false.
    • scaleFactor number (opcional) - El factor de escalado de la página web.
    • pagesPerSheet number (opcional) - El número de páginas a imprimir por hoja de página.
    • collate boolean (opcional) - Si la página web debe ser intercalada.
    • copies number (opcional) - El número de copias de la página web a imprimir.
    • pageRanges Object[] (optional) - The page range to print.
      • from number - Index of the first page to print (0-based).
      • to number - Índice de la última página a imprimir (inclusive) (0-based).
    • duplexMode string (optional) - Set the duplex mode of the printed web page. Puede ser simplex, shortEdge, o longEdge.
    • dpi Record<string, number\> (optional)
      • horizontal number (opcional) - El dpi horizontal.
      • vertical number (opcional) - El dpi vertical.
    • header string (opcional) - Cadena a ser impresa como cabecera de la página.
    • footer string (opcional) - Cadena a ser impresa como pie de página.
    • pageSize string | Tamaño (opcional) - Especifique el tamaño de página del documento impreso. Can be A3, A4, A5, Legal, Letter, Tabloid or an Object containing height in microns.

Devuelve Promise<void>

Imprime la página web de webview. Igual que webContents.print([options]).

<webview>.printToPDF(opciones)

  • options Object
    • landscape boolean (optional) - Paper orientation.true for landscape, false for portrait. Por defecto es falso.
    • displayHeaderFooter boolean (optional) - Whether to display header and footer. Por defecto es falso.
    • printBackground boolean (optional) - Whether to print background graphics. Por defecto es falso.
    • scale number(optional) - Scale of the webpage rendering. Defaults to 1.
    • pageSize string | Size (opcional) - Especifique el tamaño de la pagina PDF generada. Can be A0, A1, A2, A3, A4, A5, A6, Legal, Letter, Tabloid, Ledger, or an Object containing height and width in inches. Por defecto es Letter.
    • margins Object (opcional)
      • top number (optional) - Top margin in inches. Defaults to 1cm (~0.4 inches).
      • bottom number (optional) - Bottom margin in inches. Defaults to 1cm (~0.4 inches).
      • left number (optional) - Left margin in inches. Defaults to 1cm (~0.4 inches).
      • right number (optional) - Right margin in inches. Defaults to 1cm (~0.4 inches).
    • pageRanges string (optional) - Page ranges to print, e.g., '1-5, 8, 11-13'. Defaults to the empty string, which means print all pages.
    • headerTemplate string (optional) - HTML template for the print header. Should be valid HTML markup with following classes used to inject printing values into them: date (formatted print date), title (document title), url (document location), pageNumber (current page number) and totalPages (total pages in the document). For example, <span class=title></span> would generate span containing the title.
    • footerTemplate string (optional) - HTML template for the print footer. Should use the same format as the headerTemplate.
    • preferCSSPageSize boolean (optional) - Whether or not to prefer page size as defined by css. Defaults to false, in which case the content will be scaled to fit the paper size.
    • generateTaggedPDF boolean (optional) Experimental - Whether or not to generate a tagged (accessible) PDF. Por defecto es falso. As this property is experimental, the generated PDF may not adhere fully to PDF/UA and WCAG standards.
    • generateDocumentOutline boolean (optional) Experimental - Whether or not to generate a PDF document outline from content headers. Por defecto es falso.

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

Imprime la página web de webview como PDF, Igual como webContents.printToPDF(options).

<webview>.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. Omitir rect capturará toda la página visible.

<webview>.send(channel, ...args)

  • channel cadena
  • ...args any[]

Devuelve Promise<void>

Envía un mensaje asincrónico al proceso de renderizado a través de channel. También se puede enviar argumentos arbitrarios. El proceso renderizador puede manejar el mensaje escuchando el evento channel con el módulo ipcRenderer.

Ver webContents.send para ejemplos.

<webview>.sendToFrame(frameId, channel, ...args)

  • frameId [number, number] - [processId, frameId]
  • channel cadena
  • ...args any[]

Devuelve Promise<void>

Envía un mensaje asincrónico al proceso de renderizado a través de channel. También se puede enviar argumentos arbitrarios. El proceso renderizador puede manejar el mensaje escuchando el evento channel con el módulo ipcRenderer.

Vea webContents.sendToFrame para ejemplos.

<webview>.sendInputEvent(event)

Devuelve Promise<void>

Envía un input event a la página.

Ver webContents.sendInputEvent para una descripción detallada del objeto event.

<webview>.setZoomFactor(factor)

  • factor number - Zoom factor.

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

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

<webview>.getZoomFactor()

Devuelve number - el factor de zoom actual.

<webview>.getZoomLevel()

Devuelve number - el nivel de zoom actual.

<webview>.setVisualZoomLevelLimits(minimumLevel, maximumLevel)

  • minimumLevel número
  • maximumLevel número

Devuelve Promise<void>

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

<webview>.showDefinitionForSelection() macOS

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

<webview>.getWebContentsId()

Devuelve number - El ID de WebContents de este webview.

Eventos DOM

Los siguientes eventos DOM están disponibles en la etiqueta webview:

Evento: 'load-commit'

Devuelve:

  • url string
  • isMainFrame boolean

Fired when a load has committed. This includes navigation within the current document as well as subframe document-level loads, but does not include asynchronous resource loads.

Evento: 'did-finish-load'

Disparado cuando la navegación es terminada, i.e. el girador del tabulador dejará de girar, y el evento onload es discapacitado.

Evento: 'did-fail-load'

Devuelve:

  • errorCode Integer
  • errorDescription string
  • validatedURL string
  • isMainFrame boolean

Este evento es como did-finish-load,pero disparado cuando la carga falla o es cancelada, e.g. window.stop() es involucrada.

Evento: 'did-frame-finish-load'

Devuelve:

  • isMainFrame boolean

Disparado cuando un frame ha terminado la navegación.

Evento: 'did-start-loading'

Corresponde a los puntos en tiempo cuando el girador del tabulador empieza a girar.

Evento: 'did-stop-loading'

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

Evento: 'did-attach'

Fired when attached to the embedder web contents.

Evento: 'dom-ready'

Disparado cuando el documento en el frame dado es cargado.

Evento: 'page-title-updated'

Devuelve:

  • title string
  • explicitSet boolen

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

Evento: 'page-favicon-updated'

Devuelve:

  • favicons string[] - matriz de URLs.

Disparado cuando la página recibe urls de favicon.

Evento: "enter-html-full-screen"

Disparado cuando la página entra en pantalla entera i¿y es activado por HTML API.

Evento: "leave-html-full-screen"

Disparado cuando la página deja la pantalla completa activada por HTML API.

Evento: 'console-message'

Devuelve:

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

Disparado cuando la ventana invitada entra un mensaje de consola.

El siguiente código ejemplo sigue con todos los mensajes guardados a la consola embebedora sin preocupación por el nivel de guardado u otras propiedades.

const webview = document.querySelector('webview')
webview.addEventListener('console-message', (e) => {
console.log('Guest page logged a message:', e.message)
})

Evento: 'found-in-page'

Devuelve:

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

Disparado cuando un resultado es disponible en la solicitud webview.findInPage.

const webview = document.querySelector('webview')
webview.addEventListener('found-in-page', (e) => {
webview.stopFindInPage('keepSelection')
})

const requestId = webview.findInPage('test')
console.log(requestId)

Evento: 'will-navigate'

Devuelve:

  • 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 <webview>.loadURL y <webview>.back.

It is also not emitted during in-page navigation, such as clicking anchor links or updating the window.location.hash. Use did-navigate-in-page event for this purpose.

Llamar a event.preventDefault(), NO tiene ningún efecto.

Event: 'will-frame-navigate'

Devuelve:

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

Emitted when a user or the page wants to start navigation anywhere in the <webview> or any frames embedded within. It can happen when the window.location object is changed or a user clicks a link in the page.

Este evento no se emitirá cuando la navegación es iniciada con programación con APIs como <webview>.loadURL y <webview>.back.

It is also not emitted during in-page navigation, such as clicking anchor links or updating the window.location.hash. Use did-navigate-in-page event for this purpose.

Llamar a event.preventDefault(), NO tiene ningún efecto.

Evento: 'did-start-navigation'

Devuelve:

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

Emitido cuando cualquier frame (incluyendo el principal) comienza la navegación. isInPlace will be true for in-page navigations.

Evento: 'did-redirect-navigation'

Devuelve:

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

Emitted after a server side redirect occurs during navigation. For example a 302 redirect.

Evento: 'did-navigate'

Devuelve:

  • url string

Emitido cuando la navegación es finalizada.

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:

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

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

This event is not emitted for in-page navigations, such as clicking anchor links or updating the window.location.hash. Use did-navigate-in-page event for this purpose.

Evento: 'did-navigate-in-page'

Devuelve:

  • isMainFrame boolean
  • url string

Emitido cuando una navegación dentro de la página sucede.

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: "close"

Disparado cuando la página de invitado intenta cerrarse.

El siguiente código ejemplo navega el webview a about:blank cuando el invitado intenta cerrase.

const webview = document.querySelector('webview')
webview.addEventListener('close', () => {
webview.src = 'about:blank'
})

Evento: 'ipc-message'

Devuelve:

  • frameId [number, number] - pair of [processId, frameId].
  • channel cadena
  • args any[]

Disparado cuando la página de invitado ha enviado un mensaje asincrónico a la página de embebido.

Con el método sendToHost y el evento ipc-message puedes comunicarte entre la página de invitado y la página del integrador:

// In embedder page.
const webview = document.querySelector('webview')
webview.addEventListener('ipc-message', (event) => {
console.log(event.channel)
// Prints "pong"
})
webview.send('ping')
// In guest page.
const { ipcRenderer } = require('electron')
ipcRenderer.on('ping', () => {
ipcRenderer.sendToHost('pong')
})

Evento: 'render-process-gone'

Devuelve:

Fired when the renderer process unexpectedly disappears. Esto se debe comúnmente porque se crasheo o cerro.

Evento: 'plugin-crashed'

Devuelve:

  • name string
  • version cadena

Disparado cuando el proceso de plugin se cae.

Evento: 'destroyed'

Disparado cuando el WebContents es destrozado.

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:

  • themeColor cadena

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:

  • url string

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

Event: 'devtools-open-url'

Devuelve:

  • url string - URL of the link that was clicked or selected.

Emitted when a link is clicked in DevTools or 'Open in new tab' is selected for a link in its context menu.

Event: 'devtools-search-query'

Devuelve:

  • event
  • query string - text to query for.

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

Evento: 'devtools-opened'

Emitido cuando DevTools es abierto.

Evento: 'devtools-closed'

Emitido cuando Devtools es cerrado.

Evento: 'devtools-focused'

Emitido cuando DevTools es centrado o abierto.

Evento: 'context-menu'

Devuelve:

  • params Object
    • x Integer - x coordinate.
    • y Integer - y coordinate.
    • linkURL string - URL of the link that encloses the node the context menu was invoked on.
    • linkText string - Text associated with the link. May be an empty string if the contents of the link are an image.
    • pageURL string - URL of the top level page that the context menu was invoked on.
    • frameURL string - URL of the subframe that the context menu was invoked on.
    • srcURL string - Source URL for the element that the context menu was invoked on. Elements with source URLs are images, audio and video.
    • mediaType string - Type of the node the context menu was invoked on. Puede ser none, image, audio, video, canvas, file o plugin.
    • hasImageContents boolean - Whether the context menu was invoked on an image which has non-empty contents.
    • isEditable boolean - Whether the context is editable.
    • selectionText string - Text of the selection that the context menu was invoked on.
    • titleText string - Title text of the selection that the context menu was invoked on.
    • altText string - Alt text of the selection that the context menu was invoked on.
    • suggestedFilename string - Suggested filename to be used when saving file through 'Save Link As' option of context menu.
    • selectionRect Rectangle - Rect representing the coordinates in the document space of the selection.
    • selectionStartOffset number - Start position of the selection text.
    • referrerPolicy Referrer - The referrer policy of the frame on which the menu is invoked.
    • misspelledWord string - The misspelled word under the cursor, if any.
    • dictionarySuggestions string[] - An array of suggested words to show the user to replace the misspelledWord. Solo disponible si hay una palabra mal escrita y el corrector está habilitado.
    • frameCharset string - The character encoding of the frame on which the menu was invoked.
    • formControlType string - The source that the context menu was invoked on. Possible values include none, button-button, field-set, input-button, input-checkbox, input-color, input-date, input-datetime-local, input-email, input-file, input-hidden, input-image, input-month, input-number, input-password, input-radio, input-range, input-reset, input-search, input-submit, input-telephone, input-text, input-time, input-url, input-week, output, reset-button, select-list, select-list, select-multiple, select-one, submit-button, and text-area,
    • spellcheckEnabled boolean - If the context is editable, whether or not spellchecking is enabled.
    • menuSourceType string - Input source that invoked the context menu. Puede ser none, mouse, keyboard, touch, touchMenu, longPress, longTap, touchHandle, stylus, adjustSelection, o adjustSelectionReset.
    • mediaFlags Object - The flags for the media element the context menu was invoked on.
      • inError boolean - Whether the media element has crashed.
      • isPaused boolean - Whether the media element is paused.
      • isMuted boolean - Whether the media element is muted.
      • hasAudio boolean - Whether the media element has audio.
      • isLooping boolean - Whether the media element is looping.
      • isControlsVisible boolean - Whether the media element's controls are visible.
      • canToggleControls boolean - Whether the media element's controls are toggleable.
      • canPrint boolean - Whether the media element can be printed.
      • canSave boolean - Whether or not the media element can be downloaded.
      • canShowPictureInPicture boolean - Whether the media element can show picture-in-picture.
      • isShowingPictureInPicture boolean - Whether the media element is currently showing picture-in-picture.
      • canRotate boolean - Whether the media element can be rotated.
      • canLoop boolean - Whether the media element can be looped.
    • editFlags Object - These flags indicate whether the renderer believes it is able to perform the corresponding action.
      • canUndo boolean - Whether the renderer believes it can undo.
      • canRedo boolean - Whether the renderer believes it can redo.
      • canCut boolean - Whether the renderer believes it can cut.
      • canCopy boolean - Whether the renderer believes it can copy.
      • canPaste boolean - Whether the renderer believes it can paste.
      • canDelete boolean - Whether the renderer believes it can delete.
      • canSelectAll boolean - Whether the renderer believes it can select all.
      • canEditRichly boolean - Whether the renderer believes it can edit text richly.

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