Aller au contenu principal

webFrameMain

Accéder aux pages web et aux iframes.

Process: Main

The webFrameMain module can be used to lookup frames across existing WebContents instances. Son utilisation la plus courante est lors des événements de navigation. .

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éthodes

Ces méthodes sont accessibles depuis le module webFrameMain :

webFrameMain.fromId(processId, routingId)

  • processId Integer - Un Integer représentant l'ID interne du processus qui possède la frame.
  • routingId Integer - Un Integer représentant l'ID unique dde la frame dans le processus de rendu courant . Les identifiants de routage peuvent être récupérés à partir des instances de WebFrameMain (frame.routingId) et sont également transmis par les événements spécifiques du WebContents de la frame (par ex. did-frame-navigate).

Retourne WebFrameMain | undefined - Une frame avec les identifiants de processus et de routage, ou undefined s'il n'y a pas d'identifiant WebFrameMain associé aux identifiants donnés.

webFrameMain.fromFrameToken(processId, frameToken)

  • processId Integer - Un Integer représentant l'ID interne du processus qui possède la 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.

Class: WebFrameMain

Process: Main
This class is not exported from the 'electron' module. Elle n'est disponible qu'en tant que valeur de retour des autres méthodes de l'API Electron.

Événements d’instance

Événement : 'dom-ready'

Émis lorsque le document est chargé.

Méthodes d’instance

frame.executeJavaScript(code[, userGesture])

  • code string
  • userGesture boolean (facultatif) - false par défaut.

Retourne Promise<unknown> - Une promesse qui se résout avec le résultat du code exécuté ou se rejette si le résultat du code est une promesse rejetée.

Évalue le code dans la page.

Dans la fenêtre du navigateur, certaines APIs HTML comme requestFullScreen peut être invoqué seulement par un geste de l'utilisateur. Définir userGesture à true supprimera cette limitation.

frame.reload()

Retourne boolean - Indique si le rechargement a été initié avec succès. Ne retourne false uniquement lorsque la frame n'a pas d'historique.

frame.isDestroyed()

Returns boolean - Whether the frame is destroyed.

frame.send(channel, ...args)

  • channel string
  • ...args any[]

Envoyez un message asynchrone et un certain nombre d'arguments au processus de rendu via channel. . 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.

Le processus de rendu peut gérer le message en écoutant sur le channel avec le module ipcRenderer .

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

  • channel string
  • message any
  • transfer MessagePortMain[] (facultatif)

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

Les objets MessagePortMain transférés seront disponibles dans le processus de rendu en accédant à la propriété ports de l'événement émis. Ils seront des objets DOM MessagePort natifs en arrivant dans le moteur de rendu.

Par exemple :

// 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. false par défaut.
    • displayHeaderFooter boolean (optional) - Whether to display header and footer. false par défaut.
    • printBackground boolean (optional) - Whether to print background graphics. false par défaut.
    • scale number(optional) - Scale of the webpage rendering. 1 par défaut.
    • 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. 1cm par défaut (~0.4 pouce).
      • bottom number (optional) - Bottom margin in inches. 1cm par défaut (~0.4 pouce).
      • left number (optional) - Left margin in inches. 1cm par défaut (~0.4 pouce).
      • right number (optional) - Right margin in inches. 1cm par défaut (~0.4 pouce).
    • pageRanges string (optional) - Page ranges to print, e.g., '1-5, 8, 11-13'. Par défaut: une chaîne vide, signifiant d'afficher toutes les 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. Faux par défaut, auquel cas le contenu sera mis à l'échelle pour s'adapter à la taille du papier.
    • generateTaggedPDF boolean (optional) Experimental - Whether or not to generate a tagged (accessible) PDF. false par défaut. 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. false par défaut.

Retourne une Promise<Buffer> -se résolvant avec les données PDF générées.

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.

Le landscape sera ignoré si la règle CSS de @page est utilisée dans la page 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)
})
})
})

Voir Page.printToPdf pour plus d'informations.

Propriétés d'instance

frame.ipc Readonly

An IpcMain instance scoped to the frame.

Les messages IPC envoyés en invoquant ipcRenderer.send, ipcRenderer.sendSync ou ipcRenderer.postMessage seront envoyés dans l'ordres suivant :

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

Les gestionnaires enregistrés pour invoke seront vérifiés dans la commande suivante. Le premier défini sera appelé, le reste sera ignoré.

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

Dans la plupart des cas, seul la frame principale d'un WebContents peut envoyer ou recevoir des messages IPC. Toutefois si l'option nodeIntegrationInSubFrames est activée il sera également possible pour les frames enfants d'envoyer et de recevoir des messages IPC. The WebContents.ipc interface may be more convenient when nodeIntegrationInSubFrames is not enabled.

frame.url Readonly

string représentant l'URL actuelle du cadre.

frame.origin Readonly

string représentant l’origine actuelle de la frame elle est sérialisée conformément à la RFC 6454. Cela peut être différent de l'URL. Par exemple, si la frame est une fenêtre enfant ouverte avec about:blank, alors frame.origin retournera l'origine de la frame parente, tandis que frame.url retournera une chaîne vide. Les pages sans la triple origine schéma/hôte/port auront l’origine sérialisée de "null" (c’est-à-dire la chaîne contenant les lettres n, u, l, l).

frame.top Readonly

WebFrameMain | null représentant la frame de plus haut niveau dans la hiérarchie des frames à laquelle appartient frame .

frame.parent Readonly

WebFrameMain | null représentant la frame parente de frame, la propriété sera null si frame est la frame de plus haut niveau de la hiérarchie.

frame.frames Readonly

Collection de WebFrameMain[] contenant les descendants directs de frame.

frame.framesInSubtree Readonly

A WebFrameMain[] collection containing every frame in the subtree of frame, including itself. Cela peut être utile lors d'un parcours à travers toutes les frames.

frame.frameTreeNodeId Readonly

Integer représentant l'id du FrameTreeNode interne de la frame . Cet id est global au navigateur et identifie de manière unique une frame qui héberge du contenu . L'identifiant est fixé lors de la création de la frame et demeure constant pendant l'existence de celle-ci. Lorsque la frame est supprimée, l'id n'est pas réutilisé.

frame.name Readonly

string représentant le nom de la frame.

frame.frameToken Lecture seule

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

frame.osProcessId Readonly

Integer représentant le pid du processus qui possède cette frame.

frame.processId Readonly

Integer représentant le pid du processus propriétaire de cette frame interne à Chromium. Ce n'est pas le même que l'identifiant du processus de l'OS ; pour lire celui-ci vous devez utiliser, frame.osProcessId.

frame.routingId Readonly

Integer représentant l'ID unique de la frame dans le processus de rendu courant. Les instances distinctes de WebFrameMain faisant référence à la même frame sous-jacente auront le même routingId.

frame.visibilityState Readonly

string représentant l'état de visibilité de la frame.

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

frame.detached Lecture seule

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.