Saltar al contenido principal

webFrameMain

Control web pages and iframes.

Proceso: principal

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)
}
}
)

You can also access frames of existing pages by using the mainFrame property of 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.

webFrameMain.fromFrameToken(processId, frameToken)

  • processId Integer - Un Integer representando el ID interno del proceso que posee el frame.
  • frameToken string - A string token identifying the unique frame. Can also be retrieved in the renderer process via webFrame.frameToken.

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

Clase: WebFrameMain

Process: Main
This class is not exported from the 'electron' module. Sólo está disponible como un valor de retorno de otros métodos en la API de Electron.

Eventos de Instancia

Evento: '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.isDestroyed()

Returns boolean - Whether the frame is destroyed.

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. Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will throw an exception.

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
// ...
})

frame.collectJavaScriptCallStack() Experimental

Returns Promise<string> | Promise<void> - A promise that resolves with the currently running JavaScript call stack. If no JavaScript runs in the frame, the promise will never resolve. In cases where the call stack is otherwise unable to be collected, it will return undefined.

This can be useful to determine why the frame is unresponsive in cases where there's long-running JavaScript. For more information, see the proposed Crash Reporting API.

const { app } = require('electron')

app.commandLine.appendSwitch('enable-features', 'DocumentPolicyIncludeJSCallStacksInCrashReports')

app.on('web-contents-created', (_, webContents) => {
webContents.on('unresponsive', async () => {
// Interrupt execution and collect call stack from unresponsive renderer
const callStack = await webContents.mainFrame.collectJavaScriptCallStack()
console.log('Renderer unresponsive\n', callStack)
})
})

frame.copyVideoFrameAt(x, y)

  • x Integer
  • y Integer

When executed on a video media element, copies the frame at (x, y) to the clipboard.

frame.saveVideoFrameAs(x, y)

  • x Integer
  • y Integer

When executed on a video media element, shows a save dialog and saves the frame at (x, y) to disk.

frame.printToPDF(options)

History
Version(s)Changes
None
API ADDED
  • options PrintToPDFOptions
    • 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 (optional) - Specify page size of the generated PDF. Can be A0, A1, A2, A3, A4, A5, A6, Legal, Letter, Tabloid, Ledger, or an Object containing height and width in inches. Defaults to Letter.
    • margins PrintToPDFMargins (optional)
      • 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<Buffer> - Se resuelve cuando los datos PDF son generados.

Prints the frame's web page as PDF.

Unlike webContents.printToPDF, this method prints only the contents of the frame it is called on. This can be used to print an individual <iframe> from the main process.

El landscape se ignorará si @page CSS at-rule es utilizado en la página web.

An example of printing an iframe to PDF:

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

const fs = require('node:fs')
const os = require('node:os')
const path = require('node:path')

app.whenReady().then(() => {
const win = new BrowserWindow()
win.loadFile('page-with-iframe.html')

win.webContents.on('did-finish-load', () => {
const pdfPath = path.join(os.homedir(), 'Desktop', 'iframe.pdf')
const iframe = win.webContents.mainFrame.frames[0]
iframe.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.

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.frameToken SoloLectura

A string which uniquely identifies the frame within its associated renderer process. This is equivalent to webFrame.frameToken.

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.

frame.detached SoloLectura

A Boolean representing whether the frame is detached from the frame tree. If a frame is accessed while the corresponding page is running any unload listeners, it may become detached as the newly navigated page replaced it in the frame tree.