Saltar al contenido principal

webFrameMain

Control web pages and iframes.

Proceso: principal</0>

The webFrameMain module can be used to lookup frames across existing WebContents instances. Navigation events are the common use case.

const { BrowserWindow, webFrameMain } = require('electron')

const win = new BrowserWindow({ width: 800, height: 1500 })
win.loadURL('https://twitter.com')

win.webContents.on(
'did-frame-navigate',
(event, url, httpResponseCode, httpStatusText, isMainFrame, frameProcessId, frameRoutingId) => {
const frame = webFrameMain.fromId(frameProcessId, frameRoutingId)
if (frame) {
const code = 'document.body.innerHTML = document.body.innerHTML.replaceAll("heck", "h*ck")'
frame.executeJavaScript(code)
}
}
)

También puedes acceder a los frames de una página existente usando la propiedad mainFrame de WebContents.

const { BrowserWindow } = require('electron')

async function main () {
const win = new BrowserWindow({ width: 800, height: 600 })
await win.loadURL('https://reddit.com')

const youtubeEmbeds = win.webContents.mainFrame.frames.filter((frame) => {
try {
const url = new URL(frame.url)
return url.host === 'www.youtube.com'
} catch {
return false
}
})

console.log(youtubeEmbeds)
}

main()

Métodos

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

webFrameMain.fromId(processId, routingId)

  • processId Integer - Un Integer representando el ID interno del proceso que posee el frame.
  • routingId Integer - Un Integer representando el ID único del frame en el renderer process actual. Routing IDs can be retrieved from WebFrameMain instances (frame.routingId) and are also passed by frame specific WebContents navigation events (e.g. did-frame-navigate).

Returns WebFrameMain | undefined - A frame with the given process and routing IDs, or undefined if there is no WebFrameMain associated with the given IDs.

Clase: WebFrameMain

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: 'dom-ready'

Emitido cuando es documento está cargado.

Métodos de Instancia

frame.executeJavaScript(code[, userGesture])

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

Returns Promise<unknown> - A promise that resolves with the result of the executed code or is rejected if execution throws or results in a rejected promise.

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.

frame.reload()

Devuelve boolean - Si la recarga fue iniciada correctamente. Solo resulta en false cuando el frame no tiene historial.

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

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

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

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

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

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

Por ejemplo:

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

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

Propiedades de la instancia

frame.ipc Readonly

An IpcMain instance scoped to the frame.

IPC messages sent with ipcRenderer.send, ipcRenderer.sendSync or ipcRenderer.postMessage will be delivered in the following order:

  1. contents.on('ipc-message')
  2. contents.mainFrame.on(channel)
  3. contents.ipc.on(channel)
  4. ipcMain.on(channel)

Handlers registered with invoke will be checked in the following order. The first one that is defined will be called, the rest will be ignored.

  1. contents.mainFrame.handle(channel)
  2. contents.handle(channel)
  3. ipcMain.handle(channel)

In most cases, only the main frame of a WebContents can send or receive IPC messages. However, if the nodeIntegrationInSubFrames option is enabled, it is possible for child frames to send and receive IPC messages also. The WebContents.ipc interface may be more convenient when nodeIntegrationInSubFrames is not enabled.

frame.url Readonly

Un string representando la URL actual del frame.

frame.origin Readonly

A string representing the current origin of the frame, serialized according to RFC 6454. This may be different from the URL. For instance, if the frame is a child window opened to about:blank, then frame.origin will return the parent frame's origin, while frame.url will return the empty string. Pages without a scheme/host/port triple origin will have the serialized origin of "null" (that is, the string containing the letters n, u, l, l).

frame.top Readonly

Un WebFrameMain | null representando el frame superior en la jerarquía a la que pertenece el frame.

frame.parent Readonly

Un WebFrameMain | null representando al frame padre de frame, la propiedad debería ser null si el frame es el frame superior en la jerarquía de frame.

frame.frames Readonly

Una colección WebFrameMain[] que contiene los descendientes directos del frame.

frame.framesInSubtree Readonly

Una colección WebFrameMain[] que contiene cada frame en el subárbol de frame incluyendo el mismo. Esto puede resultar útil al atravesar todos los frames.

frame.frameTreeNodeId Readonly

Un Integer que representa el id de la instancia FrameTreeNode del frame. Este id es global del navegador y unicamente identifica a un frame que aloja contenido. El identificador se fija en la creación del frame y permanece constante por durante el ciclo de vida del frame. Cuando el frame es eliminado, el id no se vuelve a utilizar.

frame.name Readonly

A string representing the frame name.

frame.osProcessId Readonly

Un Integer que representa el pid del proceso del sistema operativo al cual pertenece este frame.

frame.processId Readonly

Un Integer que representa el pid del proceso interno de Chromium al cual pertenece este frame. Esto no es el mismo que el process ID del sistema operativo; para leer eso use frame.osProcessId.

frame.routingId Readonly

An Integer representing the unique frame id in the current renderer process. Las instancias distintas de WebFrameMain que se refieren al mimo frame subyacente tendrán el mismo routingId.

frame.visibilityState Readonly

Un string que representa el visibility state del frame.

See also how the Page Visibility API is affected by other Electron APIs.