<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. For more information see the BrowserWindow constructor docs.
Descripción general
Mostrar contenido externo de la web en un cuadro aislado y procesado.
Process: Renderer
This class is not exported from the 'electron' module. Sólo está disponible como un valor de retorno de otros métodos en la API de Electron.
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] Most methods called on the webview from the host page require a synchronous call to the main process.
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 awebview. - Usted puede no agregar escuchadores de eventos de teclado, mouse y scroll a
webview. - Todas las reacciones entre el frame embebedor y el
webviewson 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. The full list of supported preference strings can be found in BrowserWindow.
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:
[!NOTE] The webview element must be loaded before using the methods.
Ejemplo
const webview = document.querySelector('webview')
webview.addEventListener('dom-ready', () => {
webview.openDevTools()
})
<webview>.loadURL(url[, options])
urlURL
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).
Carga el url en el webview, el url debe contener el prefijo protocolo, e.g. el http:// or file://.
<webview>.downloadURL(url[, options])
urlstring
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)
userAgentcadena
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)
csscadena
Devuelve Promise<string> - Una promesa que resuelve con una llave para el CSS insertado que puede ser utilizado más tarde para eliminar el CSS a través <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)
llavecadena
Devuelve Promise<void> - Resuelve si la eliminación fue exitosa.
Elimina el CSS insertado desde la página web actual. La hoja de estilos se identifica por su clave, el cual es devuelto desde <webview>.insertCSS(css).
<webview>.executeJavaScript(code[, userGesture])
codigostringuserGestureboolean (opcional) - Predeterminadofalse.
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)
xIntegeryInteger
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)
mutedboolean
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)
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)
textocadena
Ejecuta el comando de edición replace en página.
<webview>.replaceMisspelling(text)
textocadena
Ejecuta el comando de edición replaceMisspelling en página.
<webview>.insertText(text)
textocadena
Devuelve Promise<void>
Inserta texto en el elemento enfocado.
<webview>.findInPage(text[, options])
textstring - El contenido para ser buscado, no debe quedar en blanco.
Devuelve Integer - El id de la solicitud usado para la solicitud.
Empieza una solicitud para encontrar todas las coincidencias para el text en la página web. The result of the request can be obtained by subscribing to found-in-page event.
<webview>.stopFindInPage(action)
actionstring - Specifies the action to take place when ending<webview>.findInPagerequest.clearSelection- Borrar la selección.keepSelection- Traduce la selección en una selección normal.activateSelection- Enfoca y hace clic en el nodo de selección.
Detiene cualquier solicitud findInPage para el webview con la action dada.
<webview>.print([options])
Devuelve Promise<void>
Imprime la página web de webview. Igual que webContents.print([options]).
<webview>.printToPDF(opciones)
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])
rectRectangle (optional) - The area of the page to be captured.
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)
channelcadena...argsany[]
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. The renderer process can handle the message by listening to the channel event with the ipcRenderer module.
See webContents.send for examples.
<webview>.sendToFrame(frameId, channel, ...args)
frameId[number, number] -[processId, frameId]channelcadena...argsany[]
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. The renderer process can handle the message by listening to the channel event with the ipcRenderer module.
See webContents.sendToFrame for examples.
<webview>.sendInputEvent(event)
Devuelve Promise<void>
Envía un input event a la página.
See webContents.sendInputEvent for detailed description of event object.
<webview>.setZoomFactor(factor)
factornumber - 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)
nivelnúmero - Nivel de Zoom.
Cambia el nivel de zoom al nivel especificado. El tamaño original es 0 y cada incremento por encima o por debajo representa un zoom del 20% mayor o menor a los límites predeterminados de 300% y 50% del tamaño original, respectivamente. La fórmula para esto es scale := 1.2 ^ level.
[!NOTE] The zoom policy at the Chromium level is same-origin, meaning that the zoom level for a specific domain propagates across all instances of windows with the same domain. Differentiating the window URLs will make zoom work per-window.
<webview>.getZoomFactor()
Devuelve number - el factor de zoom actual.
<webview>.getZoomLevel()
Devuelve number - el nivel de zoom actual.
<webview>.setVisualZoomLevelLimits(minimumLevel, maximumLevel)
minimumLevelnúmeromaximumLevelnú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:
urlstringisMainFrameboolean
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:
errorCodeIntegererrorDescriptionstringvalidatedURLstringisMainFrameboolean
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:
isMainFrameboolean
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:
titlestringexplicitSetboolen
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:
faviconsstring[] - 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:
levelEntero - El nivel de registro, desde 0 hasta 3. In order it matchesverbose,info,warninganderror.messagestring - The actual console messagelineEntero - El número de línea de la fuente que activó este mensaje de consolasourceIdcadena
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
resultrequestIdÍntegroactiveMatchOrdinalÍntegro - Posición de un partido activo.matchesÍntegro - Número de Coincidencias.selectionAreaRectangle - Coordenadas de la primera región de coincidencia.finalUpdateboolean
Fired when a result is available for webview.findInPage request.
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:
urlstring
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:
urlstringisMainFramebooleanframeProcessIdIntegerframeRoutingIdEntero
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:
urlstringisInPlacebooleanisMainFramebooleanframeProcessIdIntegerframeRoutingIdEntero
Emitido cuando cualquier frame (incluyendo el principal) comienza la navegación. isInPlace will be true for in-page navigations.
Evento: 'did-redirect-navigation'
Devuelve:
urlstringisInPlacebooleanisMainFramebooleanframeProcessIdIntegerframeRoutingIdEntero
Emitted after a server side redirect occurs during navigation. For example a 302 redirect.
Evento: 'did-navigate'
Devuelve:
urlstring
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:
urlstringhttpResponseCodeInteger - -1 para navegaciones no HTTPhttpStatusTextstring - empty for non HTTP navigations,isMainFramebooleanframeProcessIdIntegerframeRoutingIdEntero
Emitido cuando se ha realizado un navegación de algun frame.
This event is not emitted for in-page navigations, such as clicking anchor links or updating the window.location.hash. Use did-navigate-in-page event for this purpose.
Evento: 'did-navigate-in-page'
Devuelve:
isMainFramebooleanurlstring
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].channelcadenaargsany[]
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:
detailsRenderProcessGoneDetails
Fired when the renderer process unexpectedly disappears. Esto se debe comúnmente porque se crasheo o cerro.
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:
themeColorcadena
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:
urlstring
Emitido cuando el mouse se mueve sobre un link o el teclado se mueve el concentrado a un link.
Event: 'devtools-open-url'
Devuelve:
urlstring - 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:
eventEventquerystring - 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:
paramsObjectxInteger - x coordinate.yInteger - y coordinate.linkURLstring - URL of the link that encloses the node the context menu was invoked on.linkTextstring - Text associated with the link. May be an empty string if the contents of the link are an image.pageURLstring - URL of the top level page that the context menu was invoked on.frameURLstring - URL of the subframe that the context menu was invoked on.srcURLstring - Source URL for the element that the context menu was invoked on. Elements with source URLs are images, audio and video.mediaTypestring - Type of the node the context menu was invoked on. Puede sernone,image,audio,video,canvas,fileoplugin.hasImageContentsboolean - Whether the context menu was invoked on an image which has non-empty contents.isEditableboolean - Whether the context is editable.selectionTextstring - Text of the selection that the context menu was invoked on.titleTextstring - Title text of the selection that the context menu was invoked on.altTextstring - Alt text of the selection that the context menu was invoked on.suggestedFilenamestring - Suggested filename to be used when saving file through 'Save Link As' option of context menu.selectionRectRectangle - Rect representing the coordinates in the document space of the selection.selectionStartOffsetnumber - Start position of the selection text.referrerPolicyReferrer - The referrer policy of the frame on which the menu is invoked.misspelledWordstring - The misspelled word under the cursor, if any.dictionarySuggestionsstring[] - An array of suggested words to show the user to replace themisspelledWord. Solo disponible si hay una palabra mal escrita y el corrector está habilitado.frameCharsetstring - The character encoding of the frame on which the menu was invoked.formControlTypestring - The source that the context menu was invoked on. Possible values includenone,button-button,field-set,input-button,input-checkbox,input-color,input-date,input-datetime-local,input-email,input-file,input-hidden,input-image,input-month,input-number,input-password,input-radio,input-range,input-reset,input-search,input-submit,input-telephone,input-text,input-time,input-url,input-week,output,reset-button,select-list,select-list,select-multiple,select-one,submit-button, andtext-area,spellcheckEnabledboolean - If the context is editable, whether or not spellchecking is enabled.menuSourceTypestring - Input source that invoked the context menu. Puede sernone,mouse,keyboard,touch,touchMenu,longPress,longTap,touchHandle,stylus,adjustSelection, oadjustSelectionReset.mediaFlagsObject - The flags for the media element the context menu was invoked on.inErrorboolean - Whether the media element has crashed.isPausedboolean - Whether the media element is paused.isMutedboolean - Whether the media element is muted.hasAudioboolean - Whether the media element has audio.isLoopingboolean - Whether the media element is looping.isControlsVisibleboolean - Whether the media element's controls are visible.canToggleControlsboolean - Whether the media element's controls are toggleable.canPrintboolean - Whether the media element can be printed.canSaveboolean - Whether or not the media element can be downloaded.canShowPictureInPictureboolean - Whether the media element can show picture-in-picture.isShowingPictureInPictureboolean - Whether the media element is currently showing picture-in-picture.canRotateboolean - Whether the media element can be rotated.canLoopboolean - Whether the media element can be looped.
editFlagsObject - These flags indicate whether the renderer believes it is able to perform the corresponding action.canUndoboolean - Whether the renderer believes it can undo.canRedoboolean - Whether the renderer believes it can redo.canCutboolean - Whether the renderer believes it can cut.canCopyboolean - Whether the renderer believes it can copy.canPasteboolean - Whether the renderer believes it can paste.canDeleteboolean - Whether the renderer believes it can delete.canSelectAllboolean - Whether the renderer believes it can select all.canEditRichlyboolean - Whether the renderer believes it can edit text richly.
Emitido cuando hay un nuevo menú de contexto que debe ser manejado.