webFrameMain
控制网页和 iframe。
¥Control web pages and iframes.
进程:主进程
¥Process: Main
webFrameMain 模块可用于跨现有 WebContents 实例查找帧。导航事件是常见的用例。
¥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)
}
}
)
你还可以使用 WebContents 的 mainFrame 属性访问现有页面的框架。
¥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()
方法
¥Methods
可以从 webFrameMain 模块访问这些方法:
¥These methods can be accessed from the webFrameMain module:
webFrameMain.fromId(processId, routingId)
-
processId整数 -Integer代表拥有该帧的进程的内部 ID。¥
processIdInteger - AnIntegerrepresenting the internal ID of the process which owns the frame. -
routingId整数 -Integer代表当前渲染器进程中的唯一帧 ID。路由 ID 可以从WebFrameMain实例 (frame.routingId) 检索,也可以通过帧特定的WebContents导航事件(例如did-frame-navigate)传递。¥
routingIdInteger - AnIntegerrepresenting the unique frame ID in the current renderer process. Routing IDs can be retrieved fromWebFrameMaininstances (frame.routingId) and are also passed by frame specificWebContentsnavigation events (e.g.did-frame-navigate).
返回 WebFrameMain | undefined - 具有给定进程和路由 ID 的框架,如果没有与给定 ID 关联的 WebFrameMain,则为 undefined。
¥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代表拥有该帧的进程的内部 ID。¥
processIdInteger - AnIntegerrepresenting the internal ID of the process which owns the frame. -
frameToken字符串 -string令牌用于标识唯一帧。也可以通过webFrame.frameToken在渲染器进程中检索。¥
frameTokenstring - Astringtoken identifying the unique frame. Can also be retrieved in the renderer process viawebFrame.frameToken.
返回 WebFrameMain | null - 具有给定进程和帧令牌的帧,或者如果没有与给定 ID 关联的 WebFrameMain,则为 null。
¥Returns WebFrameMain | null - A frame with the given process and frame token,
or null if there is no WebFrameMain associated with the given IDs.
类:Web 框架主
¥Class: WebFrameMain
进程:主进程
该类不是从 'electron' 模块导出的。它仅可用作 Electron API 中其他方法的返回值。
¥Process: Main
This class is not exported from the 'electron' module. It is only available as a return value of other methods in the Electron API.
实例事件
¥Instance Events
事件:'dom-ready'
¥Event: 'dom-ready'
加载文档时发出。
¥Emitted when the document is loaded.
实例方法
¥Instance Methods
frame.executeJavaScript(code[, userGesture])
-
code字符串¥
codestring -
userGesture布尔值(可选) - 默认为false。¥
userGestureboolean (optional) - Default isfalse.
返回 Promise<unknown> - 一种根据执行代码的结果进行解析的 Promise,或者如果执行抛出或导致被拒绝的 Promise,则被拒绝。
¥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.
评估页面中的 code。
¥Evaluates code in page.
在浏览器窗口中,某些 HTML API(例如 requestFullScreen)只能通过用户的手势来调用。将 userGesture 设置为 true 将消除此限制。
¥In the browser window some HTML APIs like requestFullScreen can only be
invoked by a gesture from the user. Setting userGesture to true will remove
this limitation.
frame.reload()
返回 boolean - 重载是否启动成功。当帧没有历史记录时,仅结果为 false。
¥Returns boolean - Whether the reload was initiated successfully. Only results in false when the frame has no history.
frame.isDestroyed()
返回 boolean - 框架是否被销毁。
¥Returns boolean - Whether the frame is destroyed.
frame.send(channel, ...args)
-
channel字符串¥
channelstring -
...args任何[]¥
...argsany[]
通过 channel 将异步消息连同参数一起发送到渲染器进程。参数将与 结构化克隆算法 一起序列化,就像 postMessage 一样,因此不会包含原型链。发送函数、Promise、Symbols、WeakMap 或 WeakSet 将引发异常。
¥Send an asynchronous message to the renderer process via channel, along with
arguments. 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.
渲染器进程可以通过使用 ipcRenderer 模块监听 channel 来处理消息。
¥The renderer process can handle the message by listening to channel with the
ipcRenderer module.
frame.postMessage(channel, message, [transfer])
-
channel字符串¥
channelstring -
message任意¥
messageany -
transferMessagePortMain[](可选)¥
transferMessagePortMain[] (optional)
向渲染器进程发送消息,可选择转移零个或多个 MessagePortMain 对象的所有权。
¥Send a message to the renderer process, optionally transferring ownership of
zero or more MessagePortMain objects.
通过访问触发事件的 ports 属性,传输的 MessagePortMain 对象将在渲染器进程中可用。当它们到达渲染器时,它们将是原生 DOM MessagePort 对象。
¥The transferred MessagePortMain objects will be available in the renderer
process by accessing the ports property of the emitted event. When they
arrive in the renderer, they will be native DOM MessagePort objects.
例如:
¥For example:
// 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() 实验性的
¥frame.collectJavaScriptCallStack() Experimental
返回 Promise<string> | Promise<void> - 使用当前运行的 JavaScript 调用堆栈解析的 promise。如果框架中没有运行 JavaScript,则 promise 永远不会解决。在无法收集调用堆栈的情况下,它将返回 undefined。
¥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.
这对于确定在长时间运行 JavaScript 的情况下框架无响应的原因很有用。有关更多信息,请参阅 建议的崩溃报告 API。
¥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)
})
})
实例属性
¥Instance Properties
frame.ipc 只读
¥frame.ipc Readonly
范围为框架的 IpcMain 实例。
¥An IpcMain instance scoped to the frame.
使用 ipcRenderer.send、ipcRenderer.sendSync 或 ipcRenderer.postMessage 发送的 IPC 消息将按以下顺序传递:
¥IPC messages sent with ipcRenderer.send, ipcRenderer.sendSync or
ipcRenderer.postMessage will be delivered in the following order:
contents.on('ipc-message')contents.mainFrame.on(channel)contents.ipc.on(channel)ipcMain.on(channel)
将按以下顺序检查在 invoke 上注册的处理程序。第一个定义的将被调用,其余的将被忽略。
¥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.
contents.mainFrame.handle(channel)contents.handle(channel)ipcMain.handle(channel)
在大多数情况下,只有 WebContents 的主框架可以发送或接收 IPC 消息。然而,如果启用了 nodeIntegrationInSubFrames 选项,子帧也可以发送和接收 IPC 消息。当 nodeIntegrationInSubFrames 未启用时,WebContents.ipc 接口可能会更方便。
¥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 只读
¥frame.url Readonly
string 代表框架的当前 URL。
¥A string representing the current URL of the frame.
frame.origin 只读
¥frame.origin Readonly
string 代表帧的当前原点,根据 RFC 6454 进行序列化。这可能与 URL 不同。例如,如果框架是向 about:blank 打开的子窗口,则 frame.origin 将返回父框架的原点,而 frame.url 将返回空字符串。没有方案/主机/端口三重源的页面将具有 "null" 的序列化源(即包含字母 n、u、l、l 的字符串)。
¥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 只读
¥frame.top Readonly
WebFrameMain | null 代表 frame 所属的帧层次结构中的顶层帧。
¥A WebFrameMain | null representing top frame in the frame hierarchy to which frame
belongs.
frame.parent 只读
¥frame.parent Readonly
WebFrameMain | null 代表 frame 的父框架,如果 frame 是框架层次结构中的顶层框架,则属性将为 null。
¥A WebFrameMain | null representing parent frame of frame, the property would be
null if frame is the top frame in the frame hierarchy.
frame.frames 只读
¥frame.frames Readonly
包含 frame 直系后代的 WebFrameMain[] 系列。
¥A WebFrameMain[] collection containing the direct descendents of frame.
frame.framesInSubtree 只读
¥frame.framesInSubtree Readonly
包含 frame 子树中每个帧(包括其自身)的 WebFrameMain[] 集合。这在遍历所有帧时非常有用。
¥A WebFrameMain[] collection containing every frame in the subtree of frame,
including itself. This can be useful when traversing through all frames.
frame.frameTreeNodeId 只读
¥frame.frameTreeNodeId Readonly
Integer 代表框架内部 FrameTreeNode 实例的 id。该 ID 是浏览器全局的,唯一标识托管内容的框架。标识符在帧创建时固定,并在帧的生命周期内保持不变。当框架被移除时,该 id 就不再使用。
¥An Integer representing the id of the frame's internal FrameTreeNode
instance. This id is browser-global and uniquely identifies a frame that hosts
content. The identifier is fixed at the creation of the frame and stays
constant for the lifetime of the frame. When the frame is removed, the id is
not used again.
frame.name 只读
¥frame.name Readonly
string 代表框架名称。
¥A string representing the frame name.
frame.frameToken 只读
¥frame.frameToken Readonly
string 在其关联的渲染进程中唯一标识帧。这相当于 webFrame.frameToken。
¥A string which uniquely identifies the frame within its associated renderer
process. This is equivalent to webFrame.frameToken.
frame.osProcessId 只读
¥frame.osProcessId Readonly
Integer 代表拥有该帧的进程的操作系统 pid。
¥An Integer representing the operating system pid of the process which owns this frame.
frame.processId 只读
¥frame.processId Readonly
Integer 代表拥有该框架的进程的 Chromium 内部 pid。这与操作系统进程 ID 不同;要阅读该内容,请使用 frame.osProcessId。
¥An Integer representing the Chromium internal pid of the process which owns this frame.
This is not the same as the OS process ID; to read that use frame.osProcessId.
frame.routingId 只读
¥frame.routingId Readonly
Integer 代表当前渲染器进程中的唯一帧 ID。引用相同底层框架的不同 WebFrameMain 实例将具有相同的 routingId。
¥An Integer representing the unique frame id in the current renderer process.
Distinct WebFrameMain instances that refer to the same underlying frame will
have the same routingId.
frame.visibilityState 只读
¥frame.visibilityState Readonly
string 代表帧的 可见性状态。
¥A string representing the visibility state of the frame.
另请参阅 页面可见性 API 如何受到其他 Electron API 的影响。
¥See also how the Page Visibility API is affected by other Electron APIs.
frame.detached 只读
¥frame.detached Readonly
Boolean 表示框架是否与框架树分离。如果在相应页面运行任何 unload 监听器时访问框架,则该框架可能会分离,因为新导航的页面在框架树中替换了它。
¥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.