webFrameMain¶
控制网页和 iframe。
进程:主进程
webFrameMain 模块可用于在现有的 WebContents 实例中查找 frame。导航事件是常见用例。
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)
}
}
)
你还可以通过 WebContents 的 mainFrame 属性访问现有页面中的 frame。
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()
方法¶
可以从 webFrameMain 模块访问以下方法:
webFrameMain.fromId(processId, routingId)¶
processIdInteger - 一个Integer,表示拥有该 frame 的进程的内部 ID。routingIdInteger - 一个Integer,表示当前渲染器进程中唯一的 frame ID。可以从WebFrameMain实例(frame.routingId)获取 routing ID,它们也会由特定 frame 的WebContents导航事件(例如did-frame-navigate)传递。
返回 WebFrameMain | undefined - 具有给定进程和 routing ID 的 frame;如果给定 ID 没有关联的 WebFrameMain,则返回 undefined。
webFrameMain.fromFrameToken(processId, frameToken)¶
processIdInteger - 一个Integer,表示拥有该 frame 的进程的内部 ID。frameTokenstring - 用于标识唯一 frame 的string令牌。也可以通过在渲染器进程中的webFrame.frameToken获取。
返回 WebFrameMain | null - 具有给定进程和 frame token 的 frame;如果给定 ID 没有关联的 WebFrameMain,则返回 null。
类:WebFrameMain¶
进程:主进程
此类不会从 'electron' 模块中导出。它只能作为 Electron API 中其他方法的返回值使用。
实例事件¶
事件:'dom-ready'¶
当文档加载完成时触发。
实例方法¶
frame.executeJavaScript(code[, userGesture])¶
codestringuserGestureboolean (optional) - 默认为false。
返回 Promise<unknown> - 一个 promise,解析为所执行代码的结果;如果执行抛出异常或导致 promise 被拒绝,则会拒绝该 promise。
在页面中执行 code。
在浏览器窗口中,某些 HTML API(如 requestFullScreen)只能由用户手势调用。将 userGesture 设置为 true 会消除此限制。
frame.reload()¶
返回 boolean - 重新加载是否已成功发起。仅当 frame 没有历史记录时才会返回 false。
frame.isDestroyed()¶
返回 boolean - frame 是否已销毁。
frame.send(channel, ...args)¶
channelstring...argsany[]
通过 channel 向渲染器进程发送异步消息,并附带参数。参数将使用 结构化克隆算法 进行序列化,就像 [postMessage][] 一样,因此不会包含原型链。发送 Functions、Promises、Symbols、WeakMaps 或 WeakSets 将抛出异常。
渲染器进程可以使用 ipcRenderer 模块监听 channel 来处理消息。
frame.postMessage(channel, message, [transfer])¶
channelstringmessageanytransferMessagePortMain[] (optional)
向渲染器进程发送消息,并可选地转让零个或多个 [MessagePortMain][] 对象的所有权。
传输的 MessagePortMain 对象在渲染器进程中可通过访问所触发事件的 ports 属性来获取。当它们到达渲染器时,它们将是原生 DOM MessagePort 对象。
例如:
// 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() 实验性¶
返回 Promise<string> | Promise<void> - 一个 promise,解析为当前正在运行的 JavaScript 调用堆栈。如果 frame 中没有 JavaScript 在运行,该 promise 将永远不会解析。在无法收集调用堆栈的其他情况下,它将返回 undefined。
这在存在长时间运行的 JavaScript 时可能有助于确定 frame 无响应的原因。更多信息,请参阅提议的崩溃报告 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)¶
xIntegeryInteger
在视频媒体元素上执行时,将 (x, y) 处的帧复制到剪贴板。
frame.saveVideoFrameAs(x, y)¶
xIntegeryInteger
在视频媒体元素上执行时,将显示一个保存对话框,并将 (x, y) 处的帧保存到磁盘。
frame.printToPDF(options)¶
<!-- ```YAML history added: - pr-url: https://github.com/electron/electron/pull/52439
-->
* `options` [PrintToPDFOptions](structures/print-to-pdf-options.md?inline)
返回 `Promise<Buffer>` - 使用生成的 PDF 数据解析。
将帧的网页打印为 PDF。
与 [`webContents.printToPDF`](web-contents.md#contentsprinttopdfoptions) 不同,此方法仅打印在其上调用该方法的帧的内容。这可用于从主进程打印单个 `<iframe>`。
如果在网页中使用了 `@page` CSS 规则,则 `landscape` 将被忽略。
以下是将 iframe 打印为 PDF 的示例:
```js
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)
})
})
})
有关更多信息,请参阅 Page.printToPdf。
实例属性¶
frame.ipc 只读¶
一个限定于该帧作用域的 IpcMain 实例。
使用 ipcRenderer.send、ipcRenderer.sendSync 或 ipcRenderer.postMessage 发送的 IPC 消息将按以下顺序传递:
contents.on('ipc-message')contents.mainFrame.on(channel)contents.ipc.on(channel)ipcMain.on(channel)
使用 invoke 注册的处理程序将按以下顺序检查。第一个已定义的处理程序将被调用,其余将被忽略。
contents.mainFrame.handle(channel)contents.handle(channel)ipcMain.handle(channel)
在大多数情况下,只有 WebContents 的主帧才能发送或接收 IPC 消息。但是,如果启用了 nodeIntegrationInSubFrames 选项,子帧也有可能发送和接收 IPC 消息。当未启用 nodeIntegrationInSubFrames 时,WebContents.ipc 接口可能更方便。
frame.url 只读¶
一个 string,表示帧当前的 URL。
frame.origin 只读¶
一个 string,表示帧当前的源,根据 RFC 6454 序列化。这可能与 URL 不同。例如,如果帧是打开到 about:blank 的子窗口,则 frame.origin 将返回父帧的源,而 frame.url 将返回空字符串。没有 scheme/host/port 三元组源的页面将具有序列化源 "null"(即包含字母 n、u、l、l 的字符串)。
frame.top 只读¶
一个 WebFrameMain | null,表示 frame 所属帧层次结构中的顶层帧。
frame.parent 只读¶
一个 WebFrameMain | null,表示 frame 的父帧。如果 frame 是帧层次结构中的顶层帧,则该属性为 null。
frame.frames 只读¶
一个 WebFrameMain[] 集合,包含 frame 的直接后代。
frame.framesInSubtree 只读¶
一个 WebFrameMain[] 集合,包含 frame 子树中的每个帧,包括其自身。这在遍历所有帧时非常有用。
frame.frameTreeNodeId 只读¶
一个 Integer,表示帧的内部 FrameTreeNode 实例的 id。此 id 在浏览器范围内全局唯一,用于唯一标识承载内容的帧。该标识符在帧创建时固定,并在帧的整个生命周期内保持不变。当帧被移除后,该 id 不会再次使用。
frame.name 只读¶
一个 string,表示帧名称。
frame.frameToken 只读¶
一个 string,在关联的渲染器进程内唯一标识该帧。这等效于 webFrame.frameToken。
frame.osProcessId 只读¶
一个 Integer,表示拥有此帧的进程的操作系统 pid。
frame.processId 只读¶
一个 Integer,表示拥有此帧的进程的 Chromium 内部 pid。这与操作系统进程 ID 不同;要读取该 ID,请使用 frame.osProcessId。
frame.routingId 只读¶
一个 Integer,表示当前渲染器进程中的唯一帧 id。引用同一底层帧的不同 WebFrameMain 实例将具有相同的 routingId。
frame.visibilityState 只读¶
一个 string,表示帧的可见性状态。
另请参阅 Page Visibility API 如何受其他 Electron API 的影响。
frame.detached 只读¶
一个 Boolean,表示帧是否已从帧树中分离。如果在相应页面正在运行任何 unload 监听器时访问帧,则由于新导航的页面在帧树中替换了该帧,该帧可能会变为分离状态。
本页原文 Markdown:在 AtomGit 查看·内容源自开源项目 el/electron