webFrameMain
控制网页和iframe。
进程:主进程
🌐 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。routingId整数 - 一个Integer,表示当前渲染器进程中唯一的帧 ID。路由 ID 可以从WebFrameMain实例(frame.routingId)中获取,并且也会通过特定帧的WebContents导航事件(例如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。frameToken字符串 - 一个string令牌,用于标识唯一的帧。也可以通过渲染进程中的webFrame.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.
类:WebFrameMain
🌐 Class: WebFrameMain
进程: 主进程
此类未从 'electron' 模块导出。它仅作为 Electron API 中其他方法的返回值提供。
实例事件
🌐 Instance Events
Event: 'dom-ready'
加载文档时发出。
🌐 Emitted when the document is loaded.
实例方法
🌐 Instance Methods
frame.executeJavaScript(code[, userGesture])
code字符串userGesture布尔值(可选)- 默认值为false。
返回 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字符串...argsany[]
通过 channel 向渲染进程发送异步消息,同时附带参数。参数将使用 结构化克隆算法 序列化,就像 postMessage 一样,因此原型链将不会被包含。发送函数、Promise、Symbol、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字符串message任何transferMessagePortMain[](可选)
向渲染进程发送消息,可选择转移零个或多个 MessagePortMain 对象的所有权。
🌐 Send a message to the renderer process, optionally transferring ownership of
zero or more MessagePortMain objects.
传输的 MessagePortMain 对象可以通过访问触发事件的 ports 属性在渲染进程中使用。当它们到达渲染器时,它们将是原生 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 调用栈。如果框架中没有 JavaScript 运行,该承诺将永远不会解析。在无法收集调用栈的情况下,它将返回 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
一个表示拥有此帧的进程的操作系统 pid 的 Integer。
🌐 An Integer representing the operating system pid of the process which owns this frame.
frame.processId 只读
🌐 frame.processId Readonly
一个 Integer,表示拥有此框架的进程的 Chromium 内部 pid。这不同于操作系统进程 ID;要读取操作系统进程 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.
另请参阅其他 Electron API 如何影响 页面可见性 API。
🌐 See also how the Page Visibility API is affected by other Electron APIs.
frame.detached 只读
🌐 frame.detached Readonly
Boolean 表示该框架是否已从框架树中分离。如果在对应页面正在运行任何 卸载 监听器时访问某个框架,该框架可能会在新导航的页面替换它进入框架树时变为分离状态。
🌐 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.