从渲染进程打开窗口
有几种方法可以控制如何在渲染器中从可信或不可信的内容创建窗口。窗口可以通过两种方式从渲染器创建:
- 点击带有
target=_blank
的链接或提交表单 - JavaScript 调用
window.open()
对于同源内容,新窗口会在同一进程中创建,允许父窗口直接访问子窗口。这对于充当偏好设置面板或类似功能的应用程序子窗口非常有用,因为父窗口可以直接渲染到子窗口,就好像它是父窗口中的一个 div
一样。这与浏览器中的行为相同。
Electron 在底层将此原生 Chrome Window
与 BrowserWindow 配对。通过使用 webContents.setWindowOpenHandler()
来处理由渲染器创建的窗口,您可以利用在主进程中创建 BrowserWindow 时可用的所有自定义选项。
BrowserWindow 构造函数选项的设置顺序(按优先级递增):window.open()
中 features
字符串解析出的选项、从父窗口继承的安全相关的 webPreferences,以及 webContents.setWindowOpenHandler
提供的选项。请注意,webContents.setWindowOpenHandler
拥有最终决定权和完全的权限,因为它是在主进程中调用的。
window.open(url[, frameName][, features])
url
stringframeName
字符串 (可选)features
字符串 (可选)
返回 Window
| null
features
是一个逗号分隔的键值对列表,遵循浏览器的标准格式。Electron 将尽可能从列表中解析出 BrowserWindowConstructorOptions
,以方便使用。为了获得完全的控制和更好的用户体验,请考虑使用 webContents.setWindowOpenHandler
来自定义 BrowserWindow 的创建。
WebPreferences
的一部分可以通过 features
字符串直接设置,无需嵌套:zoomFactor
、nodeIntegration
、preload
、javascript
、contextIsolation
和 webviewTag
。
例如
window.open('https://github.com', '_blank', 'top=500,left=200,frame=false,nodeIntegration=no')
备注
- 如果父窗口禁用了 Node.js 集成,那么在打开的
window
中 Node.js 集成也将始终被禁用。 - 如果父窗口启用了上下文隔离,那么在打开的
window
中上下文隔离也将始终被启用。 - 如果父窗口禁用了 JavaScript,那么在打开的
window
中 JavaScript 也将始终被禁用。 - 在
features
中提供的非标准功能(未被 Chromium 或 Electron 处理的功能)将被传递到任何已注册的webContents
的did-create-window
事件处理程序的options
参数中。 frameName
遵循 原生文档 中target
的规范。- 当打开
about:blank
时,子窗口的WebPreferences
将从父窗口复制,并且无法覆盖,因为在这种情况下 Chromium 会跳过浏览器端的导航。
要自定义或取消窗口的创建,您可以选择在主进程中使用 webContents.setWindowOpenHandler()
设置一个覆盖处理程序。返回 { action: 'deny' }
会取消窗口。返回 { action: 'allow', overrideBrowserWindowOptions: { ... } }
会允许打开窗口,并设置创建窗口时使用的 BrowserWindowConstructorOptions
。请注意,这比通过功能字符串传递选项更强大,因为渲染器在决定安全偏好方面的权限比主进程有限。
除了传递 action
和 overrideBrowserWindowOptions
之外,还可以像这样传递 outlivesOpener
:{ action: 'allow', outlivesOpener: true, overrideBrowserWindowOptions: { ... } }
。如果设置为 true
,则新创建的窗口在打开器窗口关闭时不会关闭。默认值为 false
。
原生 Window
示例
// main.js
const mainWindow = new BrowserWindow()
// In this example, only windows with the `about:blank` url will be created.
// All other urls will be blocked.
mainWindow.webContents.setWindowOpenHandler(({ url }) => {
if (url === 'about:blank') {
return {
action: 'allow',
overrideBrowserWindowOptions: {
frame: false,
fullscreenable: false,
backgroundColor: 'black',
webPreferences: {
preload: 'my-child-window-preload-script.js'
}
}
}
}
return { action: 'deny' }
})
// renderer process (mainWindow)
const childWindow = window.open('', 'modal')
childWindow.document.write('<h1>Hello</h1>')