window.open 函数

打开一个新窗口并加载 URL。

当调用 window.open 以在网页中创建新窗口时,将为url创建一个新的BrowserWindow 实例,并返回一个代理至 window.open 以让页面对其进行有限的控制。

The proxy has limited standard functionality implemented to be compatible with traditional web pages. For full control of the new window you should create a BrowserWindow directly.

The newly created BrowserWindow will inherit the parent window’s options by default. To override inherited options you can set them in the features string.

window.open(url[, frameName][, features])

  • url String
  • frameName String(可选)
  • features String(可选)

Returns BrowserWindowProxy - 创建一个新窗口,并返回一个 BrowserWindowProxy 类的实例。

features 字符串遵循标准浏览器的格式,但每个 feature 必须是BrowserWindow 选项中的字段。 These are the features you can set via features string: zoomFactor, nodeIntegration, preload, javascript, contextIsolation, webviewTag.

例如:

  1. window.open('https://github.com', '_blank', 'nodeIntegration=no')

注意:

  • 如果在父窗口中禁用了 Node integration, 则在打开的 window 中将始终被禁用。
  • 如果在父窗口中启用了上下文隔离, 则在打开的 window 中将始终被启用。
  • 父窗口禁用 Javascript,打开的 window 中将被始终禁用
  • features 中给定的非标准特性 (不由 Chromium 或 Electron 处理) 将被传递到 additionalFeatures 参数中的任何已注册 webContentnew-window 事件处理程序。

window.opener.postMessage(message, targetOrigin)

  • message String
  • targetOrigin String

将消息发送给指定来源的父窗口,如果未指定来源则发送给*,即所有窗口。

使用 Chrome 的 window.open()

如果要使用 Chrome 的内置 window.open(),请在 webPreferences 选项中将 nativeWindowOpen 设置为 true

原生 window.open () 允许同步打开窗口, 因此可以方便的选择是对话框还是首选项窗口。

该选项也可以设置在<webview>标签上:

  1. <webview webpreferences="nativeWindowOpen=yes"></webview>

BrowserWindow的创建可通过WebContentsnew-window事件进行定制 。

  1. // main process
  2. const mainWindow = new BrowserWindow({
  3. width: 800,
  4. height: 600,
  5. webPreferences: {
  6. nativeWindowOpen: true
  7. }
  8. })
  9. mainWindow.webContents.on('new-window', (event, url, frameName, disposition, options, additionalFeatures) => {
  10. if (frameName === 'modal') {
  11. // open window as modal
  12. event.preventDefault()
  13. Object.assign(options, {
  14. modal: true,
  15. parent: mainWindow,
  16. width: 100,
  17. height: 100
  18. })
  19. event.newGuest = new BrowserWindow(options)
  20. }
  21. })
  1. // renderer process (mainWindow)
  2. let modal = window.open('', 'modal')
  3. modal.document.write('<h1>Hello</h1>')