跳转至

session

管理浏览器会话、Cookie、缓存、代理设置等。

进程:主进程

session 模块可用于创建新的 Session 对象。

你还可以通过使用 WebContents 的 session 属性,或从 session 模块访问现有页面的 session。

const { BrowserWindow } = require('electron')

const win = new BrowserWindow({ width: 800, height: 600 })
win.loadURL('https://github.com')

const ses = win.webContents.session
console.log(ses.getUserAgent())

方法

session 模块具有以下方法:

session.fromPartition(partition[, options])

  • partition 字符串
  • options 对象(可选)
  • cache 布尔值 - 是否启用缓存。默认值为 true,除非使用了 --disable-http-cache 开关。

返回 Session - 来自 partition 字符串的会话实例。如果已存在具有相同 partition 的 Session,则返回该实例;否则将使用 options 创建一个新的 Session 实例。

如果 partition 以 persist: 开头,页面将使用一个持久会话,该会话可供应用中具有相同 partition 的所有页面使用。如果没有 persist: 前缀,页面将使用内存会话。如果 partition 为空,则返回应用的默认会话。

若要使用 options 创建 Session,必须确保具有该 partition 的 Session 之前从未被使用过。无法更改现有 Session 对象的 options。

session.fromPath(path[, options])

  • path 字符串
  • options 对象(可选)
  • cache 布尔值 - 是否启用缓存。默认值为 true,除非使用了 --disable-http-cache 开关。

返回 Session - 来自 path 字符串指定的绝对路径的会话实例。如果已存在具有相同绝对路径的 Session,则返回该实例;否则将使用 options 创建一个新的 Session 实例。如果路径不是绝对路径,该调用将抛出错误。此外,如果提供空字符串,也会抛出错误。

若要使用 options 创建 Session,必须确保具有该 path 的 Session 之前从未被使用过。无法更改现有 Session 对象的 options。

属性

session 模块具有以下属性:

session.defaultSession

一个 Session 对象,即应用的默认会话对象,在调用 app.whenReady 后可用。

类:Session

获取和设置会话的属性。

进程:主进程
此类未从 'electron' 模块导出。它仅可作为 Electron API 中其他方法的返回值使用。

你可以在 session 模块中创建 Session 对象:

const { session } = require('electron')

const ses = session.fromPartition('persist:name')
console.log(ses.getUserAgent())

实例事件

Session 的实例上可用以下事件:

事件:'will-download'

<!-- ``YAML history changes: - pr-url: https://github.com/electron/electron/pull/53685 description: "Added the trailingframe` argument."

-->

返回:

* `event` 事件
* `item` [DownloadItem](download-item.md)
* `webContents` [WebContents](web-contents.md)
* `frame` [WebFrameMain](web-frame-main.md) | null - 启动下载的 frame,如果它仍然存在。

当 Electron 即将在 `webContents` 中下载 `item` 时发出。另请参阅
[`item.getInitiatorOrigin()`](download-item.md#downloaditemgetinitiatororigin)。

调用 `event.preventDefault()` 将取消下载,并且从进程的下一个 tick 开始,`item` 将不可用。

```js @ts-expect-error=[5]
const { session } = require('electron')

session.defaultSession.on('will-download', (event, item, webContents) => {
  event.preventDefault()
  require('got')(item.getURL()).then((response) => {
    require('node:fs').writeFileSync('/somewhere', response.body)
  })
})

事件:'extension-loaded'

返回:

在扩展加载后发出。每当有扩展被添加到“已启用”扩展集合时,就会发生这种情况。这包括:

  • 从 Session.loadExtension 加载的扩展。
  • 正在重新加载的扩展:
  • 从崩溃中恢复。
  • 如果扩展请求了它(chrome.runtime.reload())。

事件:'extension-unloaded'

返回:

在扩展卸载后发出。当调用 Session.removeExtension 时,就会发生这种情况。

事件:'extension-ready'

返回:

在扩展加载完成,并且所有必要的浏览器状态都已初始化以支持扩展后台页面启动后发出。

事件:'file-system-access-restricted'

<!-- ``YAML history changes: - pr-url: https://github.com/electron/electron/pull/53666 description: "Addeddetails.frameanddetails.webContents`; emitted once per requesting document instead of once per path."

-->

返回:

* `event` 事件
* `details` 对象
  * `origin` 字符串 - 发起访问被阻止路径的源。
  * `isDirectory` 布尔值 - 路径是否为目录。
  * `path` 字符串 - 尝试访问的被阻止路径。
  * `frame` [WebFrameMain](web-frame-main.md) | null - 发起访问的 frame。如果该 frame 此后已被销毁,则可能为 `null`。
  * `webContents` [WebContents](web-contents.md) | null - 包含 `frame` 的 WebContents。
* `callback` 函数
  * `action` 字符串 - 针对受限路径访问尝试所采取的操作。
    * `allow` - 这将允许访问 `path`,尽管其处于受限状态。
    * `deny` - 这将阻止访问请求并触发 [`AbortError`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort)。
    * `tryAgain` - 这将打开一个新的文件选择器,并允许用户选择另一个路径。



```js
const { app, dialog, BrowserWindow, session } = require('electron')

async function createWindow () {
  const mainWindow = new BrowserWindow()

  await mainWindow.loadURL('https://buzzfeed.com')

  session.defaultSession.on('file-system-access-restricted', async (e, details, callback) => {
    const { origin, path } = details
    const { response } = await dialog.showMessageBox({
      message: `Are you sure you want ${origin} to open restricted path ${path}?`,
      title: 'File System Access Restricted',
      buttons: ['Choose a different folder', 'Allow', 'Cancel'],
      cancelId: 2
    })

    if (response === 0) {
      callback('tryAgain')
    } else if (response === 1) {
      callback('allow')
    } else {
      callback('deny')
    }
  })

  mainWindow.webContents.executeJavaScript(`
    window.showDirectoryPicker({
      id: 'electron-demo',
      mode: 'readwrite',
      startIn: 'downloads',
    }).catch(e => {
      console.log(e)
    })`, true
  )
}

app.whenReady().then(() => {
  createWindow()

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})

事件:'preconnect'

<!-- ``YAML history changes: - pr-url: https://github.com/electron/electron/pull/53685 description: "Added the trailingframe` argument."

-->

返回:

* `event` Event
* `preconnectUrl` string - 渲染进程请求预连接的 URL。
* `allowCredentials` boolean - 如果渲染进程请求连接包含凭据,则为 true(有关更多详细信息,请参阅[规范](https://w3c.github.io/resource-hints/#preconnect)。)
* `frame` [WebFrameMain](web-frame-main.md) | null - 请求预连接的框架,如果该框架仍然存在。

当渲染进程请求预连接到某个 URL 时发出,通常是由于[资源提示](https://w3c.github.io/resource-hints/)。

#### 事件:'spellcheck-dictionary-initialized' {#event-spellcheck-dictionary-initialized}

返回:

* `event` Event
* `languageCode` string - 词典文件的语言代码

当 hunspell 词典文件成功初始化时发出。这发生在文件下载之后。

#### 事件:'spellcheck-dictionary-download-begin' {#event-spellcheck-dictionary-download-begin}

返回:

* `event` Event
* `languageCode` string - 词典文件的语言代码

当 hunspell 词典文件开始下载时发出

#### 事件:'spellcheck-dictionary-download-success' {#event-spellcheck-dictionary-download-success}

返回:

* `event` Event
* `languageCode` string - 词典文件的语言代码

当 hunspell 词典文件成功下载时发出

#### 事件:'spellcheck-dictionary-download-failure' {#event-spellcheck-dictionary-download-failure}

返回:

* `event` Event
* `languageCode` string - 词典文件的语言代码

当 hunspell 词典文件下载失败时发出。 有关失败详情,应收集 netlog 并检查下载请求。

#### 事件:'select-hid-device' {#event-select-hid-device}

返回:

* `event` Event
* `details` Object
  * `deviceList` [HIDDevice[]](structures/hid-device.md)
  * `frame` [WebFrameMain](web-frame-main.md) | null - 发起此事件的框架。
      如果访问时框架已经导航或已被销毁,则可能为 `null`。
* `callback` Function
  * `deviceId` string | null(可选)

当调用 `navigator.hid.requestDevice` 时需要选择 HID 设备时发出。应使用要选择的 `deviceId` 调用 `callback`;不向 `callback` 传递任何参数将取消请求。 此外,可以使用 [`ses.setPermissionCheckHandler(handler)`](#sessetpermissioncheckhandlerhandler) 和 [`ses.setDevicePermissionHandler(handler)`](#sessetdevicepermissionhandlerhandler) 进一步管理 `navigator.hid` 的权限。

```js @ts-type={fetchGrantedDevices:()=>(Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)}
const { app, BrowserWindow } = require('electron')

let win = null

app.whenReady().then(() => {
  win = new BrowserWindow()

  win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
    if (permission === 'hid') {
      // Add logic here to determine if permission should be given to allow HID selection
      return true
    }
    return false
  })

  // Optionally, retrieve previously persisted devices from a persistent store
  const grantedDevices = fetchGrantedDevices()

  win.webContents.session.setDevicePermissionHandler((details) => {
    if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'hid') {
      if (details.device.vendorId === 123 && details.device.productId === 345) {
        // Always allow this type of device (this allows skipping the call to `navigator.hid.requestDevice` first)
        return true
      }

      // Search through the list of devices that have previously been granted permission
      return grantedDevices.some((grantedDevice) => {
        return grantedDevice.vendorId === details.device.vendorId &&
              grantedDevice.productId === details.device.productId &&
              grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber
      })
    }
    return false
  })

  win.webContents.session.on('select-hid-device', (event, details, callback) => {
    event.preventDefault()
    const selectedDevice = details.deviceList.find((device) => {
      return device.vendorId === 9025 && device.productId === 67
    })
    callback(selectedDevice?.deviceId)
  })
})

事件:'hid-device-added'

返回:

  • event Event
  • details Object
  • device HIDDevice
  • frame WebFrameMain | null - 发起此事件的框架。 如果访问时框架已经导航或已被销毁,则可能为 null。

在调用 navigator.hid.requestDevice 并且 select-hid-device 已触发后,如果在来自 select-hid-device 的回调被调用之前有新设备可用,则发出。 此事件旨在 用于使用 UI 询问用户选择设备时,以便 UI 可以 使用新添加的设备进行更新。

事件:'hid-device-removed'

返回:

  • event 事件
  • details 对象
  • device HIDDevice
  • frame WebFrameMain | null - 触发此事件的帧。 如果在该帧导航或销毁后访问,可能为 null。

在调用 navigator.hid.requestDevice 并且 select-hid-device 已触发后发出,如果在调用 select-hid-device 的回调之前设备已被移除。此事件旨在用于使用 UI 提示用户选择设备时,以便更新 UI 以移除指定设备。

事件:'hid-device-revoked'

返回:

  • event 事件
  • details 对象
  • device HIDDevice
  • origin 字符串(可选) - 该设备被撤销权限的来源。

在调用 HIDDevice.forget() 后发出。当使用 setDevicePermissionHandler 时,此事件可用于帮助维护权限的持久化存储。

事件:'select-serial-port'

返回:

当调用 navigator.serial.requestPort 时需要选择串行端口时发出。应使用要选择的 portId 调用 callback,向 callback 传递空字符串将取消请求。此外,可以使用 ses.setPermissionCheckHandler(handler) 配合 serial 权限来管理 navigator.serial 的权限。

```js @ts-type={fetchGrantedDevices:()=>(Array)} const { app, BrowserWindow } = require('electron')

let win = null

app.whenReady().then(() => { win = new BrowserWindow({ width: 800, height: 600 })

win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => { if (permission === 'serial') { // Add logic here to determine if permission should be given to allow serial selection return true } return false })

// Optionally, retrieve previously persisted devices from a persistent store const grantedDevices = fetchGrantedDevices()

win.webContents.session.setDevicePermissionHandler((details) => { if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'serial') { if (details.device.vendorId === 123 && details.device.productId === 345) { // Always allow this type of device (this allows skipping the call to navigator.serial.requestPort first) return true }

  // Search through the list of devices that have previously been granted permission
  return grantedDevices.some((grantedDevice) => {
    return grantedDevice.vendorId === details.device.vendorId &&
          grantedDevice.productId === details.device.productId &&
          grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber
  })
}
return false

})

win.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { event.preventDefault() const selectedPort = portList.find((device) => { return device.vendorId === '9025' && device.productId === '67' }) if (!selectedPort) { callback('') } else { callback(selectedPort.portId) } }) })

#### 事件:'serial-port-added' {#event-serial-port-added}

返回:

* `event` 事件
* `port` [SerialPort](structures/serial-port.md)
* `webContents` [WebContents](web-contents.md)

在调用 `navigator.serial.requestPort` 并且 `select-serial-port` 已触发后发出,如果在调用 `select-serial-port` 的回调之前有新的串行端口可用。此事件旨在用于使用 UI 提示用户选择端口时,以便使用新添加的端口更新 UI。

#### 事件:'serial-port-removed' {#event-serial-port-removed}

返回:

* `event` 事件
* `port` [SerialPort](structures/serial-port.md)
* `webContents` [WebContents](web-contents.md)

在调用 `navigator.serial.requestPort` 并且 `select-serial-port` 已触发后发出,如果在调用 `select-serial-port` 的回调之前串行端口已被移除。此事件旨在用于使用 UI 提示用户选择端口时,以便更新 UI 以移除指定端口。

#### 事件:'serial-port-revoked' {#event-serial-port-revoked}

返回:

* `event` 事件
* `details` 对象
  * `port` [SerialPort](structures/serial-port.md)
  * `frame` [WebFrameMain](web-frame-main.md) | null - 触发此事件的帧。
      如果在该帧导航或销毁后访问,可能为 `null`。
  * `origin` 字符串 - 该设备被撤销权限的来源。

在调用 `SerialPort.forget()` 后发出。当使用 `setDevicePermissionHandler` 时,此事件可用于帮助维护权限的持久化存储。

```js
// Browser Process
const { app, BrowserWindow } = require('electron')

app.whenReady().then(() => {
  const win = new BrowserWindow({
    width: 800,
    height: 600
  })

  win.webContents.session.on('serial-port-revoked', (event, details) => {
    console.log(`Access revoked for serial device from origin ${details.origin}`)
  })
})

```js @ts-nocheck // Renderer Process

const portConnect = async () => { // Request a port. const port = await navigator.serial.requestPort()

// Wait for the serial port to open. await port.open({ baudRate: 9600 })

// ...later, revoke access to the serial port. await port.forget() }

#### 事件:'select-usb-device' {#event-select-usb-device}

返回:

* `event` 事件
* `details` 对象
  * `deviceList` [USBDevice[]](structures/usb-device.md)
  * `frame` [WebFrameMain](web-frame-main.md) | null - 触发此事件的帧。
      如果在该帧导航或销毁后访问,可能为 `null`。
* `callback` 函数
  * `deviceId` 字符串(可选)



当调用 `navigator.usb.requestDevice` 时需要选择 USB 设备时发出。调用 `callback` 时应传入要选择的 `deviceId`;不向 `callback` 传入任何参数将取消该请求。此外,可以使用 [`ses.setPermissionCheckHandler(handler)`](#sessetpermissioncheckhandlerhandler) 和 [`ses.setDevicePermissionHandler(handler)`](#sessetdevicepermissionhandlerhandler) 进一步管理 `navigator.usb` 的权限。

```js @ts-type={fetchGrantedDevices:()=>(Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)} @ts-type={updateGrantedDevices:(devices:Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)=>void}
const { app, BrowserWindow } = require('electron')

let win = null

app.whenReady().then(() => {
  win = new BrowserWindow()

  win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
    if (permission === 'usb') {
      // Add logic here to determine if permission should be given to allow USB selection
      return true
    }
    return false
  })

  // Optionally, retrieve previously persisted devices from a persistent store (fetchGrantedDevices needs to be implemented by developer to fetch persisted permissions)
  const grantedDevices = fetchGrantedDevices()

  win.webContents.session.setDevicePermissionHandler((details) => {
    if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'usb') {
      if (details.device.vendorId === 123 && details.device.productId === 345) {
        // Always allow this type of device (this allows skipping the call to `navigator.usb.requestDevice` first)
        return true
      }

      // Search through the list of devices that have previously been granted permission
      return grantedDevices.some((grantedDevice) => {
        return grantedDevice.vendorId === details.device.vendorId &&
              grantedDevice.productId === details.device.productId &&
              grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber
      })
    }
    return false
  })

  win.webContents.session.on('select-usb-device', (event, details, callback) => {
    event.preventDefault()
    const selectedDevice = details.deviceList.find((device) => {
      return device.vendorId === 9025 && device.productId === 67
    })
    if (selectedDevice) {
      // Optionally, add this to the persisted devices (updateGrantedDevices needs to be implemented by developer to persist permissions)
      grantedDevices.push(selectedDevice)
      updateGrantedDevices(grantedDevices)
    }
    callback(selectedDevice?.deviceId)
  })
})

事件:'usb-device-added'

返回值:

在调用 navigator.usb.requestDevice 并且 select-usb-device 已触发后,如果在 select-usb-device 的回调被调用之前有新设备变为可用,则发出此事件。此事件旨在用于使用 UI 提示用户选择设备的场景,以便 UI 可以使用新添加的设备进行更新。

事件:'usb-device-removed'

返回值:

在调用 navigator.usb.requestDevice 并且 select-usb-device 已触发后,如果在 select-usb-device 的回调被调用之前有设备被移除,则发出此事件。此事件旨在用于使用 UI 提示用户选择设备的场景,以便 UI 可以更新以移除指定设备。

事件:'usb-device-revoked'

返回值:

  • event Event
  • details Object
  • device USBDevice
  • origin string(可选) - 设备被撤销权限的来源。

在调用 USBDevice.forget() 后发出。当使用 setDevicePermissionHandler 时,此事件可用于帮助维护权限的持久化存储。

事件:'select-webauthn-authenticator' macOS

<!-- ```YAML history added: - pr-url: https://github.com/electron/electron/pull/51563

-->

返回值:

* `event` Event\<\>
  * `relyingPartyId` string - 来自 WebAuthn 请求的依赖方标识符。
  * `authenticators` string[] - 可用的认证器名称。可能的值为 `'touchID'` 和 `'platformPasskeys'`。
  * `frame` [WebFrameMain](web-frame-main.md) | null - 发起此事件的 frame。如果访问时 frame 已导航或已销毁,则可能为 `null`。
* `callback` Function
  * `authenticatorName` string | null(可选)

当通过 [`app.configureWebAuthn`](app.md#appconfigurewebauthnoptions-macos) 同时配置了 `touchID` 和 `platformPasskeys`,并且 WebAuthn 请求需要选择要使用的平台认证器时发出。调用 `callback` 时应传入 `event.authenticators` 中的其中一个名称;不传参数或传入不匹配的名称将取消请求,并且页面将收到 `NotAllowedError`。在监听器调用回调之前,请求会保持挂起状态,因此始终只调用一次——通常从 `try { … } finally { callback(…) }` 块中调用。如果未注册监听器,则默认使用 `platformPasskeys`;在调用回调之前抛出异常的监听器将被视为未处理,并应用默认行为。如果请求只有一个可用的认证器,则不会发出此事件,并且会自动使用该认证器。

```js
const { app, BrowserWindow } = require('electron')

app.whenReady().then(() => {
  app.configureWebAuthn({
    touchID: { keychainAccessGroup: 'A1B2C3D4E5.com.example.app.webauthn' },
    platformPasskeys: true
  })

  const win = new BrowserWindow()

  win.webContents.session.on('select-webauthn-authenticator', (event, callback) => {
    // Use the first available authenticator for the request.
    callback(event.authenticators[0])
  })
})

事件:'select-webauthn-account'

<!-- ```YAML history added: - pr-url: https://github.com/electron/electron/pull/51255

-->

返回:

* `event` Event
* `details` Object
  * `relyingPartyId` string - WebAuthn 请求中的依赖方标识符。
  * `accounts` [WebAuthnAccount[]](structures/webauthn-account.md)
  * `frame` [WebFrameMain](web-frame-main.md) | null - 触发此事件的 frame。
      如果在 frame 已导航或销毁后访问,可能为 `null`。
* `callback` Function
  * `credentialId` string | null(可选)

当对 `navigator.credentials.get()` 的调用解析出多个可发现的 WebAuthn 凭据,且用户必须选择其中一个时触发。应使用所选账户的 `credentialId` 调用 `callback`;不传参数 — 或传入与所提供账户之一不匹配的 `credentialId` — 将取消请求,页面会收到 `NotAllowedError`。凭据请求会保持挂起,直到监听器调用该回调,因此始终只调用一次 — 通常从 `try { … } finally { callback(…) }` 块中调用。

> [!NOTE]
> 如果未为此事件注册监听器,解析可发现 Touch ID 凭据的 `navigator.credentials.get()` 调用将以 `NotAllowedError` 取消 — 即使只有一个凭据匹配。如果你的应用支持可发现凭据(passkey)登录,请注册一个监听器。
> 由 `platformPasskeys` 完成的断言会在系统面板中选择账户,并且不使用此事件。

在 macOS 上,一旦通过 [`app.configureWebAuthn`](app.md#appconfigurewebauthnoptions-macos) 配置了 Touch ID 平台验证器,它就会通过此事件呈现账户。当漫游 FIDO2 验证器返回多个可发现凭据时,此事件也可能在其他平台上触发。

```js
const { app, BrowserWindow } = require('electron')

let win = null

app.whenReady().then(() => {
  app.configureWebAuthn({
    touchID: { keychainAccessGroup: 'A1B2C3D4E5.com.example.app.webauthn' }
  })

  win = new BrowserWindow()

  win.webContents.session.on('select-webauthn-account', (event, details, callback) => {
    const selected = details.accounts.find((a) => a.name === 'alice@example.com')
    callback(selected?.credentialId)
  })
})

实例方法

以下方法可用于 Session 实例:

ses.getCacheSize()

返回 Promise<Integer> - 会话当前的缓存大小,以字节为单位。

ses.clearCache()

返回 Promise<void> - 缓存清除操作完成时解析。

清除会话的 HTTP 缓存。

ses.clearStorageData([options])

  • options Object(可选)
  • origin string(可选)- 应遵循 window.location.origin 的表示形式 scheme://host:port。
  • storages string[](可选)- 要清除的存储类型,可以是 cookies、filesystem、indexdb、localstorage、 shadercache、serviceworkers、cachestorage。如果未 指定,则清除所有存储类型。

返回 Promise<void> - 存储数据清除完成时解析。

ses.flushStorageData()

将任何未写入的 DOMStorage 数据写入磁盘。

ses.setProxy(config)

返回 Promise<void> - 代理设置过程完成时解析。

设置代理配置。

你可能需要 ses.closeAllConnections 来关闭当前正在进行的连接,以防止 使用先前代理的池化套接字被后续请求复用。

ses.resolveHost(host, [options])

  • host string - 要解析的主机名。
  • options Object(可选)
  • queryType string(可选)- 请求的 DNS 查询类型。如果未指定, 解析器将根据 IPv4/IPv6 设置选择 A 或 AAAA(或两者):
    • A - 仅获取 A 记录
    • AAAA - 仅获取 AAAA 记录。
  • source string(可选)- 用于解析地址的来源。 默认允许解析器选择合适的来源。仅影响大型外部来源的使用 (例如调用系统进行解析或使用 DNS)。即使指定了来源,结果仍可能来自缓存、 解析 "localhost" 或 IP 字面量等。以下值之一:
    • any(默认)- 解析器将选择合适的来源。结果可能来自 DNS、MulticastDNS、HOSTS 文件等
    • system - 结果仅从系统或操作系统获取,例如通过 getaddrinfo() 系统调用
    • dns - 结果仅来自 DNS 查询
    • mdns - 结果仅来自多播 DNS 查询
    • localOnly - 不使用任何外部来源。结果仅来自 无论来源设置如何都可用的快速本地来源, 例如缓存、hosts 文件、IP 字面量解析等。
  • cacheUsage string(可选)- 指示可以使用哪些 DNS 缓存条目(如果有), 来提供响应。以下值之一:
    • allowed(默认)- 如果未过期,结果可能来自主机缓存
    • staleAllowed - 即使已过期(由于过期或网络变化),结果也可能来自主机缓存
    • disallowed - 结果不会来自主机缓存。
  • secureDnsPolicy string(可选)- 控制解析器针对此请求的 Secure DNS 行为。以下值之一:
    • allow(默认)
    • disable

返回 Promise<ResolvedHost> - 以 host 的已解析 IP 地址解析。

ses.resolveProxy(url)

  • url URL

返回 Promise<string> - 以 url 的代理信息解析。

ses.forceReloadProxyConfig()

返回 Promise<void> - 当代理服务的所有内部状态已重置,并且如果最新代理配置已可用则重新应用时解析。如果代理模式为 pac_script,则 PAC 脚本将再次从 pacScript 获取。

ses.setDownloadPath(path)

  • path string - 下载位置。

设置下载保存目录。默认情况下,下载目录将是相应应用文件夹下的 Downloads 文件夹。

ses.enableNetworkEmulation(options)

  • options Object
  • offline boolean (可选) - 是否模拟网络中断。默认为 false。
  • latency Double (可选) - RTT(以毫秒为单位)。默认为 0,这将禁用延迟节流。
  • downloadThroughput Double (可选) - 下载速率(单位:Bps)。默认为 0,这将禁用下载节流。
  • uploadThroughput Double (可选) - 上传速率(单位:Bps)。默认为 0,这将禁用上传节流。

使用给定的配置为 session 模拟网络。

const win = new BrowserWindow()

// To emulate a GPRS connection with 50kbps throughput and 500 ms latency.
win.webContents.session.enableNetworkEmulation({
  latency: 500,
  downloadThroughput: 6400,
  uploadThroughput: 6400
})

// To emulate a network outage.
win.webContents.session.enableNetworkEmulation({ offline: true })

ses.preconnect(options)

  • options Object
  • url string - 用于预连接的 URL。只有源(origin)与打开套接字相关。
  • numSockets number (可选) - 要预连接的套接字数量。必须介于 1 和 6 之间。默认为 1。

将给定数量的套接字预连接到某个源。

ses.closeAllConnections()

返回 Promise<void> - 当所有连接关闭时解析(resolve)。

[!NOTE] 它将终止或使当前所有进行中的请求失败。

ses.fetch(input[, init])

返回 Promise<GlobalResponse> - 参见 Response。

使用 Chromium 的网络栈发送请求,方式类似于渲染器中的 fetch()。这与 Node 的 fetch() 不同,后者使用 Node.js 的 HTTP 栈。

示例:

async function example () {
  const response = await net.fetch('https://my.app')
  if (response.ok) {
    const body = await response.json()
    // ... use the result.
  }
}

另请参阅 net.fetch(),这是一个从默认会话发出请求的便捷方法。

更多详细信息,请参阅 fetch() 的 MDN 文档。

限制:

  • net.fetch() 不支持 data: 或 blob: 协议方案。
  • integrity 选项的值会被忽略。
  • 返回的 Response 对象的 .type 和 .url 值不正确。

默认情况下,使用 net.fetch 发出的请求可以发送到自定义协议以及 file:,并且会触发 webRequest 处理程序(如果存在)。当在 RequestInit 中设置了非标准的 bypassCustomProtocolHandlers 选项时,对于此请求将不会调用自定义协议处理程序。这允许将拦截到的请求转发给内置处理程序。在绕过自定义协议时,webRequest 处理程序仍会被触发。

protocol.handle('https', (req) => {
  if (req.url === 'https://my-app.com') {
    return new Response('<body>my app</body>')
  } else {
    return net.fetch(req, { bypassCustomProtocolHandlers: true })
  }
})

ses.disableNetworkEmulation()

禁用已为 session 激活的任何网络模拟。重置为原始网络配置。

ses.setCertificateVerifyProc(proc)

  • proc Function | null
  • request Object
    • hostname string
    • certificate Certificate
    • validatedCertificate Certificate
    • isIssuedByKnownRoot boolean - 如果 Chromium 将根 CA 识别为标准根,则为 true。如果不是,则很可能是该证书由 MITM(中间人)代理生成,其根证书已在本地安装(例如由企业代理安装)。如果 verificationResult 不是 OK,则不应信任此证书。
    • verificationResult string - 如果证书受信任则为 OK,否则为类似 CERT_REVOKED 的错误。
    • errorCode Integer - 错误代码。
  • callback Function
    • verificationResult Integer - 值可以是此处列出的证书错误代码之一。除了证书错误代码之外,还可以使用以下特殊代码。
    • 0 - 表示成功并禁用证书透明度(Certificate Transparency)验证。
    • -2 - 表示失败。
    • -3 - 使用来自 Chromium 的验证结果。

为 session 设置证书验证过程(certificate verify proc)。每当请求服务器证书验证时,都会以 proc(request, callback) 的形式调用 proc。调用 callback(0) 接受证书,调用 callback(-2) 拒绝证书。

调用 setCertificateVerifyProc(null) 将恢复为默认的证书验证过程。

const { BrowserWindow } = require('electron')

const win = new BrowserWindow()

win.webContents.session.setCertificateVerifyProc((request, callback) => {
  const { hostname } = request
  if (hostname === 'github.com') {
    callback(0)
  } else {
    callback(-2)
  }
})

注意: 此过程的结果会被网络服务缓存。

ses.setPermissionRequestHandler(handler)

  • handler Function | null
  • webContents WebContents - 请求权限的 WebContents。请注意,如果请求来自子框架,则应使用 requestingUrl 来检查请求来源。
  • permission string - 所请求权限的类型。Electron 会转发 Chromium 请求的每一种权限类型,因此此列表与 Chromium 的权限类型保持一致,并包含一些在桌面上无效或仅由特定平台或功能使用的权限类型。

    • ar - 通过 WebXR Device API 请求访问增强现实会话。
    • automatic-fullscreen - 请求在未经用户事先手势的情况下进入全屏(Chromium 的自动全屏内容设置)。
    • background-fetch - 通过 Background Fetch API 请求在后台下载资源。
    • background-sync - 通过 Background Synchronization API 请求将工作推迟到用户联网时进行。
    • captured-surface-control - 通过 Captured Surface Control API 请求将滚轮事件转发到被捕获的标签页并控制其缩放级别。
    • clipboard-read - 请求读取剪贴板的访问权限。
    • clipboard-sanitized-write - 请求写入剪贴板的访问权限。
    • deprecated-sync-clipboard-read 已弃用 - 请求运行 document.execCommand("paste") 的访问权限。
    • display-capture - 通过 Screen Capture API(navigator.mediaDevices.getDisplayMedia)或通过带有 desktopCapturer 中描述的 chromeMediaSource 约束的 getUserMedia 请求捕获屏幕、窗口或标签页的访问权限。对摄像头或麦克风设备的请求将改为报告为 media。
    • fileSystem - 使用 File System API 请求读取、写入以及文件管理功能的访问权限。与 Chrome 一样,跨源 iframe 不能请求超出其已有权限的更多访问权限,并且某个源的授权在其最后一个顶层文档关闭或导航离开后不久即被重置。
    • fullscreen - 通过 Fullscreen API 请求控制应用的全屏状态。
    • geolocation - 通过 Geolocation API 请求访问用户的位置
    • geolocation-approximate - 通过 Geolocation API 请求访问用户位置的粗略近似值。
    • hand-tracking - 通过 WebXR Hand Input API 请求访问 WebXR 会话中的手部跟踪数据。
    • hid - 通过 WebHID API 请求访问 HID 设备。
    • idle-detection - 通过 IdleDetector API 请求访问用户的空闲状态。
    • keyboardLock - 通过 Keyboard Lock API 请求捕获物理键盘上任意或所有按键的按键按下事件。
    • local-fonts - 通过 Local Font Access API 请求访问用户本地安装的字体。
    • local-network - 通过 Local Network Access 请求访问用户本地网络上的设备。
    • local-network-access - 通过 Local Network Access 请求访问用户本地网络上的设备。这是原始的权限类型;较新的 Chromium 版本将其拆分为 local-network 和 loopback-network。
    • loopback-network - 通过 Local Network Access 请求访问回环(localhost)地址。
    • media - 请求访问摄像头、麦克风和扬声器等媒体设备。屏幕、窗口和标签页捕获将改为报告为 display-capture。
    • mediaKeySystem - 请求访问受 DRM 保护的内容。
    • midi - 在 Web MIDI API 中请求 MIDI 访问权限。
    • midiSysex - 在 Web MIDI API 中请求使用系统专属(SysEx)消息。
    • nfc - 通过 Web NFC API 请求访问 NFC 标签。
    • notifications - 使用 Notifications API 请求创建通知并能够在用户的系统托盘中显示通知
    • openExternal - 请求在外部应用中打开链接。
    • payment-handler - 通过 Payment Handler API 请求处理支付请求。
    • periodic-background-sync - 通过 Web Periodic Background Synchronization API 请求在后台运行定期任务。
    • persistent-storage - 通过 StorageManager.persist() 请求在存储压力下不清除该源的存储。
    • pointerLock - 通过 Pointer Lock API 请求将鼠标移动直接解释为一种输入方式。
    • screen-wake-lock - 通过 Screen Wake Lock API 请求保持屏幕唤醒。
    • sensors - 通过 Sensor APIs 请求访问加速度计和陀螺仪等设备传感器。
    • serial - 通过 Web Serial API 请求访问串行设备。
  • smart-card - 通过 Web Smart Card API 请求访问智能卡读卡器。

    • speaker-selection - 通过 speaker-selection 权限策略 请求枚举和选择音频输出设备。
    • storage-access - 允许在第三方上下文中加载的内容使用 Storage Access API 请求访问第三方 Cookie。
    • system-wake-lock - 请求保持系统唤醒而不让屏幕保持开启(系统唤醒锁)。
    • top-level-storage-access - 允许顶级网站代表来自同一相关网站集中的另一个网站的嵌入内容,使用 Storage Access API 请求第三方 Cookie 访问权限。
    • usb - 通过 WebUSB API 请求访问 USB 设备。
    • vr - 通过 WebXR Device API 请求访问虚拟现实会话。
    • web-app-installation - 通过 Web Install API 请求安装 Web 应用。
    • web-printing - 通过 Web Printing API 请求访问打印机。
    • window-management - 使用 getScreenDetails API 请求枚举屏幕的访问权限。
    • unknown - 无法识别的权限请求。
  • callback Function
    • permissionGranted boolean - 允许或拒绝该权限。
  • details PermissionRequest | FilesystemPermissionRequest | MediaAccessPermissionRequest | OpenExternalPermissionRequest - 有关所请求权限的其他信息。

设置可用于响应 session 权限请求的处理程序。 调用 callback(true) 将允许该权限,调用 callback(false) 将拒绝该权限。 要清除处理程序,请调用 setPermissionRequestHandler(null)。请注意, 你还必须实现 setPermissionCheckHandler 才能获得完整的权限处理。 大多数 Web API 会先进行权限检查,如果检查被拒绝,再发起权限请求。

const { session } = require('electron')

session.fromPartition('some-partition').setPermissionRequestHandler((webContents, permission, callback) => {
  if (webContents.getURL() === 'some-host' && permission === 'notifications') {
    return callback(false) // denied.
  }

  callback(true)
})

media 和 display-capture 请求都会携带一个 MediaAccessPermissionRequest 作为 details。media 请求用于摄像机和/或麦克风设备,而 display-capture 请求用于屏幕、窗口或标签页(无论是通过 getDisplayMedia 还是通过带有 chromeMediaSource 约束的 getUserMedia 发起)。 允许摄像机和麦克风访问但希望单独控制屏幕共享的应用程序应分别处理这两种权限:

const { session } = require('electron')

session.defaultSession.setPermissionRequestHandler((webContents, permission, callback, details) => {
  if (permission === 'media') {
    // Camera / microphone. `details.mediaTypes` lists which of them was requested.
    return callback(true)
  }
  if (permission === 'display-capture') {
    // Screen, window or tab capture.
    return callback(new URL(details.requestingUrl).origin === 'https://meet.example.com')
  }
  callback(false)
})

ses.setPermissionCheckHandler(handler)

  • handler Function\ | null
  • webContents (WebContents | null) - 包含正在检查权限的帧的 WebContents。当检查不是代表文档进行时(例如,对于 Service Worker 或 notifications 检查),此值为 null。如果检查来自子帧,则 webContents 为顶级 WebContents;使用 requestingOrigin、requestingUrl 和 isMainFrame 来标识正在请求的帧。
  • permission string - 权限检查的类型。Electron 会转发 Chromium 检查的每一种权限类型,因此此列表与 Chromium 的权限类型保持一致,并包含一些在桌面端没有效果或仅由特定平台或功能使用的类型。
    • ar - 通过 WebXR Device API 访问增强现实会话。
    • automatic-fullscreen - 无需事先用户手势即可进入全屏(Chromium 的自动全屏内容设置)。
    • background-fetch - 通过 Background Fetch API 在后台下载资源。
    • background-sync - 通过 Background Synchronization API 将工作推迟到用户具有网络连接时进行。
    • captured-surface-control - 通过 Captured Surface Control API 将滚轮事件转发到被捕获的标签页并控制其缩放级别。
    • clipboard-read - 请求读取剪贴板的访问权限。
    • clipboard-sanitized-write - 请求写入剪贴板的访问权限。
    • deprecated-sync-clipboard-read 已弃用 - 请求运行 document.execCommand("paste") 的访问权限。
    • display-capture - 通过 Screen Capture API 捕获屏幕。
    • fileSystem - 使用 File System API 访问读、写和文件管理功能。
    • fullscreen - 通过 Fullscreen API 控制应用的全屏状态。
    • geolocation - 通过 Geolocation API 访问用户的地理位置数据。
    • geolocation-approximate - 通过 Geolocation API 访问用户位置的粗略近似值。
    • hand-tracking - 通过 WebXR Hand Input API 访问 WebXR 会话中的手部跟踪数据。
    • hid - 通过 WebHID API 访问 HID 协议以操作 HID 设备。
    • idle-detection - 通过 IdleDetector API 访问用户的空闲状态。
    • keyboardLock - 通过 Keyboard Lock API 捕获物理键盘上任意或全部按键的按键事件。
    • local-fonts - 通过 Local Font Access API 访问用户本地安装的字体。
    • local-network - 通过 Local Network Access 访问用户本地网络上的设备。
    • local-network-access - 通过 Local Network Access 访问用户本地网络上的设备。这是原始的权限类型;较新的 Chromium 版本将其拆分为 local-network 和 loopback-network。
    • loopback-network - 通过 Local Network Access 访问回环(localhost)地址。
    • media - 访问媒体设备,例如摄像机、麦克风和扬声器。
    • mediaKeySystem - 访问受 DRM 保护的内容。
    • midi - 在 Web MIDI API 中启用 MIDI 访问。
    • midiSysex - 在 Web MIDI API 中使用系统专用消息。
    • nfc - 通过 Web NFC API 访问 NFC 标签。
    • notifications - 使用 Notifications API 向用户配置和显示桌面通知。
    • openExternal - 在外部应用程序中打开链接。
    • payment-handler - 通过 Payment Handler API 处理支付请求。
    • periodic-background-sync - 通过 Web Periodic Background Synchronization API 在后台运行周期性任务。
    • persistent-storage - 通过 StorageManager.persist() 在存储压力下保持源存储不被清除。
    • pointerLock - 通过 Pointer Lock API 直接将鼠标移动解释为一种输入方式。
    • screen-wake-lock - 通过 Screen Wake Lock API 保持屏幕唤醒。
    • sensors - 通过 Sensor APIs 访问设备传感器,例如加速度计和陀螺仪。
    • serial - 使用 Web Serial API 读写串行设备。
    • smart-card - 通过 Web Smart Card API 访问智能卡读卡器。
    • speaker-selection - 通过 speaker-selection 权限策略 枚举和选择音频输出设备。
    • storage-access - 允许在第三方上下文中加载的内容使用 Storage Access API 请求对第三方 Cookie 的访问权限。
    • system-wake-lock - 保持系统唤醒而不保持屏幕开启(系统唤醒锁)。
    • top-level-storage-access - 允许顶级网站代表来自同一相关网站集中的另一个网站的嵌入内容,使用 Storage Access API 请求第三方 Cookie 访问权限。
    • usb - 使用 WebUSB API 向 Web 公开非标准的通用串行总线(USB)兼容设备服务。
    • vr - 通过 WebXR Device API 访问虚拟现实会话。
    • web-app-installation - 通过 Web Install API 安装 Web 应用。
    • web-printing - 通过 Web Printing API 访问打印机。
    • window-management - 使用 getScreenDetails API 枚举屏幕。
    • unknown - 无法识别的权限检查。
  • requestingOrigin string - 权限检查的来源 URL
  • details Object - 某些属性仅适用于特定的权限类型。

    • embeddingOrigin string(可选) - 嵌入发起权限检查的帧的帧的来源。仅针对发起权限检查的跨源子帧设置。
  • securityOrigin string(可选) - 请求帧的来源,用于 media、hid、usb 和 serial 检查。

    • mediaType string(可选) - 请求的媒体访问类型,可以是 video、 audio 或 unknown。
    • requestingUrl string(可选) - 请求帧最后加载的 URL。当检查不是代表文档执行时(例如对于 service worker),不会提供。
    • isMainFrame boolean - 发起请求的帧是否为主帧。
    • filePath string(可选) - fileSystem 请求的路径。
    • isDirectory boolean(可选) - fileSystem 请求是否为目录。
    • fileAccessType string(可选) - fileSystem 请求的访问类型。可以是 writable 或 readable。

设置可用于响应 session 权限检查的处理器。 返回 true 将允许该权限,返回 false 将拒绝该权限。请注意, 您还必须实现 setPermissionRequestHandler 才能获得完整的权限处理。 大多数 Web API 会先执行权限检查,如果检查被拒绝,则会发起权限请求。 要清除处理器,请调用 setPermissionCheckHandler(null)。

const { session } = require('electron')

const url = require('node:url')

session.fromPartition('some-partition').setPermissionCheckHandler((webContents, permission, requestingOrigin) => {
  if (new URL(requestingOrigin).hostname === 'some-host' && permission === 'notifications') {
    return true // granted
  }

  return false // denied
})

[!NOTE] 由于 Chromium 的限制,fileSystem 请求的 isMainFrame 始终为 false。

ses.setDisplayMediaRequestHandler(handler[, opts])

  • handler Function | null
  • request Object
    • frame WebFrameMain | null - 正在请求访问媒体的帧。 如果帧已导航或已被销毁后访问,则可能为 null。
    • securityOrigin String - 发起请求的页面的来源。
    • videoRequested Boolean - 如果 Web 内容请求了视频流,则为 true。
    • audioRequested Boolean - 如果 Web 内容请求了音频流,则为 true。
    • userGesture Boolean - 触发此请求时是否有用户手势处于活动状态。
  • callback Function
    • streams Object
    • video Object | WebFrameMain(可选)
    • audio String | WebFrameMain(可选) - 如果 指定字符串,可以是 loopback 或 loopbackWithMute。 指定回环设备将捕获系统音频,目前 仅在 Windows 上支持。如果指定 WebFrameMain, 则将从包含该帧的 webContents 捕获音频。
    • enableLocalEcho Boolean(可选) - 如果 audio 是 WebFrameMain 且此项设置为 true,则音频的本地播放不会被静音(例如,使用 MediaRecorder 录制 WebFrameMain 并将此标志设置为 true 时,录制期间音频仍可输出到扬声器 )。默认值为 false。
  • opts Object(可选) macOS 实验性
  • useSystemPicker Boolean - 如果应使用可用的原生系统选择器,则为 true。默认值为 false。 macOS 实验性

当 Web 内容通过 navigator.mediaDevices.getDisplayMedia API 请求访问显示媒体时,将调用此处理器。使用 desktopCapturer API 选择要授予访问权限的流。

useSystemPicker 允许应用程序使用系统选择器,而不是从 getSources 提供特定的视频源。 此选项为实验性选项,目前仅适用于 MacOS 15+。如果系统选择器可用且 useSystemPicker 设置为 true,则不会调用该处理器。

const { session, desktopCapturer } = require('electron')

session.defaultSession.setDisplayMediaRequestHandler((request, callback) => {
  desktopCapturer.getSources({ types: ['screen'] }).then((sources) => {
    // Grant access to the first screen found.
    callback({ video: sources[0] })
  })
  // Use the system picker if available.
  // Note: this is currently experimental. If the system picker
  // is available, it will be used and the media request handler
  // will not be invoked.
}, { useSystemPicker: true })

将 WebFrameMain 对象作为视频或音频流传递时,会捕获包含该帧的整个 webContents(即标签页),而不仅仅是 该帧:因此,来自 <iframe> 的 request.frame 会授予该 iframe 捕获嵌入它的页面的权限。以这种方式使用之前,请检查 request.frame,并注意如果调用时帧已被销毁,回调将抛出异常。

const { session } = require('electron')

session.defaultSession.setDisplayMediaRequestHandler((request, callback) => {
  // Allow a top-level page to capture its own tab.
  if (request.frame && request.frame === request.frame.top) {
    callback({ video: request.frame })
  } else {
    callback(null)
  }
})

传递 null 而不是函数会将处理器重置为其默认状态。

ses.setDevicePermissionHandler(handler)

  • handler Function\ | null
  • details Object
    • deviceType string - 请求权限的设备类型,可以是 hid、serial 或 usb。
    • origin string - 设备权限检查的来源 URL。
    • device HIDDevice | SerialPort | USBDevice - 请求权限的设备。

设置可用于响应 session 的设备权限检查的处理程序。 返回 true 将允许该设备获得权限,返回 false 将拒绝该设备。 若要清除处理程序,请调用 setDevicePermissionHandler(null)。 此处理程序可用于向设备提供默认权限,而无需先向设备请求权限 (例如通过 navigator.hid.requestDevice)。如果未定义此处理程序,则将使用通过设备选择授予的默认设备权限 (例如通过 navigator.hid.requestDevice)。此外,Electron 的默认行为是将已授予的设备权限存储在内存中。 如果需要更长时间的存储,开发者可以存储已授予的设备权限 (例如在处理 select-hid-device 事件时),然后使用 setDevicePermissionHandler 从该存储中读取。

```js @ts-type={fetchGrantedDevices:()=>(Array)} const { app, BrowserWindow } = require('electron')

let win = null

app.whenReady().then(() => { win = new BrowserWindow()

win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => { if (permission === 'hid') { // Add logic here to determine if permission should be given to allow HID selection return true } else if (permission === 'serial') { // Add logic here to determine if permission should be given to allow serial port selection } else if (permission === 'usb') { // Add logic here to determine if permission should be given to allow USB device selection } return false })

// Optionally, retrieve previously persisted devices from a persistent store const grantedDevices = fetchGrantedDevices()

win.webContents.session.setDevicePermissionHandler((details) => { if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'hid') { if (details.device.vendorId === 123 && details.device.productId === 345) { // Always allow this type of device (this allows skipping the call to navigator.hid.requestDevice first) return true }

  // Search through the list of devices that have previously been granted permission
  return grantedDevices.some((grantedDevice) => {
    return grantedDevice.vendorId === details.device.vendorId &&
          grantedDevice.productId === details.device.productId &&
          grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber
  })
} else if (details.deviceType === 'serial') {
  if (details.device.vendorId === 123 && details.device.productId === 345) {
    // Always allow this type of device (this allows skipping the call to `navigator.hid.requestDevice` first)
    return true
  }
}
return false

})

win.webContents.session.on('select-hid-device', (event, details, callback) => { event.preventDefault() const selectedDevice = details.deviceList.find((device) => { return device.vendorId === 9025 && device.productId === 67 }) callback(selectedDevice?.deviceId) }) })

#### `ses.setUSBProtectedClassesHandler(handler)` {#ses-setusbprotectedclasseshandler-handler}

* `handler` Function\<string[]> | null
  * `details` Object
    * `protectedClasses` string[] - 当前受保护的 USB 类列表。可能的类值包括:
      * `audio`
      * `audio-video`
      * `hid`
      * `mass-storage`
      * `smart-card`
      * `video`
      * `wireless`

设置可用于覆盖哪些 [USB 类受保护](https://wicg.github.io/webusb/#usbinterface-interface) 的处理程序。
该处理程序的返回值是一个字符串数组,其中包含应被视为受保护的 USB 类(例如在渲染进程中不可用)。该数组的有效值为:

* `audio`
* `audio-video`
* `hid`
* `mass-storage`
* `smart-card`
* `video`
* `wireless`

从处理程序返回空字符串数组将允许所有 USB 类;返回传入的数组将保持默认的受保护 USB 类列表(如果未定义处理程序,这也是默认行为)。
若要清除处理程序,请调用 `setUSBProtectedClassesHandler(null)`。

```js
const { app, BrowserWindow } = require('electron')

let win = null

app.whenReady().then(() => {
  win = new BrowserWindow()

  win.webContents.session.setUSBProtectedClassesHandler((details) => {
    // Allow all classes:
    // return []
    // Keep the current set of protected classes:
    // return details.protectedClasses
    // Selectively remove classes:
    return details.protectedClasses.filter((usbClass) => {
      // Exclude classes except for audio classes
      return usbClass.indexOf('audio') === -1
    })
  })
})

ses.setBluetoothPairingHandler(handler) Windows Linux

  • handler Function | null
  • details Object
    • deviceId string
    • pairingKind string - 请求的配对提示类型。 取以下值之一:
    • confirm 此提示请求确认是否应配对蓝牙设备。
    • confirmPin 此提示请求确认所提供的 PIN 与设备上显示的 PIN 是否匹配。
    • providePin 此提示请求为设备提供 PIN。
    • frame WebFrameMain | null - 发起此处理程序的帧。 如果在帧已导航或已销毁后访问,可能为 null。
    • pin string (optional) - 如果 pairingKind 为 confirmPin,则是要验证的 PIN 值。
  • callback Function
    • response Object
    • confirmed boolean - 如果对话框被取消,应传入 false。 如果 pairingKind 为 confirm 或 confirmPin,此值应指示配对是否已确认。如果 pairingKind 为 providePin,当提供了值时,该值应为 true。
    • pin string | null (optional) - 当 pairingKind 为 providePin 时,此值应为蓝牙设备所需的 PIN。

设置一个处理程序以响应蓝牙配对请求。该处理程序 允许开发者处理在配对前需要额外验证的设备。 如果未定义处理程序,在 Linux 或 Windows 上 任何需要额外验证的配对都会自动取消。 macOS 不需要处理程序,因为 macOS 会自动处理配对。 若要清除处理程序,请调用 setBluetoothPairingHandler(null)。

const { app, BrowserWindow, session } = require('electron')

const path = require('node:path')

function createWindow () {
  let bluetoothPinCallback = null

  const mainWindow = new BrowserWindow({
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  })

  mainWindow.webContents.session.setBluetoothPairingHandler((details, callback) => {
    bluetoothPinCallback = callback
    // Send an IPC message to the renderer to prompt the user to confirm the pairing.
    // Note that this will require logic in the renderer to handle this message and
    // display a prompt to the user.
    mainWindow.webContents.send('bluetooth-pairing-request', details)
  })

  // Listen for an IPC message from the renderer to get the response for the Bluetooth pairing.
  mainWindow.webContents.ipc.on('bluetooth-pairing-response', (event, response) => {
    bluetoothPinCallback(response)
  })
}

app.whenReady().then(() => {
  createWindow()
})

ses.clearHostResolverCache()

返回 Promise<void> - 操作完成时解析。

清除主机解析器缓存。

ses.allowNTLMCredentialsForDomains(domains)

  • domains string - 启用集成身份验证的服务器列表,以逗号分隔。

动态设置是否始终为 HTTP NTLM 或 Negotiate 身份验证发送凭据。

const { session } = require('electron')
// consider any url ending with `example.com`, `foobar.com`, `baz`
// for integrated authentication.
session.defaultSession.allowNTLMCredentialsForDomains('*example.com, *foobar.com, *baz')

// consider all urls for integrated authentication.
session.defaultSession.allowNTLMCredentialsForDomains('*')

ses.setUserAgent(userAgent[, acceptLanguages])

  • userAgent string
  • acceptLanguages string(可选)

覆盖此会话的 userAgent 和 acceptLanguages。

acceptLanguages 必须是按顺序排列的、以逗号分隔的语言代码列表,例如 "en-US,fr,de,ko,zh-CN,ja"。

这不会影响现有的 WebContents,并且每个 WebContents 都可以使用 webContents.setUserAgent 来覆盖会话范围的用户代理。

ses.isPersistent()

返回 boolean - 此会话是否为持久会话。BrowserWindow 的默认 webContents 会话是持久会话。从分区创建会话时,以 persist: 为前缀的会话将是持久会话,而其他会话将是临时会话。

ses.getUserAgent()

返回 string - 此会话的用户代理。

ses.setSSLConfig(config)

  • config Object
  • minVersion string(可选)- 可以是 tls1、tls1.1、tls1.2 或 tls1.3。连接远程服务器时允许的最小 SSL 版本。默认为 tls1。
  • maxVersion string(可选)- 可以是 tls1.2 或 tls1.3。连接远程服务器时允许的最大 SSL 版本。默认为 tls1.3。
  • disabledCipherSuites Integer[](可选)- 除 net 内置策略禁用的密码套件外,还应明确禁止使用的密码套件列表。 支持的字面量形式:0xAABB,其中 AA 是 cipher_suite[0],BB 是 cipher_suite[1],如 RFC 2246 第 7.4.1.2 节所定义。无法识别但可解析的此形式密码套件不会返回错误。 示例:若要禁用 TLS_RSA_WITH_RC4_128_MD5,请指定 0x0004;若要禁用 TLS_ECDH_ECDSA_WITH_RC4_128_SHA,请指定 0xC002。 请注意,无法使用此机制禁用 TLSv1.3 密码套件。

设置会话的 SSL 配置。所有后续网络请求都将使用新配置。现有网络连接(例如 WebSocket 连接)不会被终止,但连接池中的旧套接字不会被复用于新连接。

ses.getBlobData(identifier)

  • identifier string - 有效的 UUID。

返回 Promise<Buffer> - 解析为 blob 数据。

ses.downloadURL(url[, options])

  • url string
  • options Object(可选)
  • headers Record\<string, string>(可选)- HTTP 请求头。

开始下载 url 处的资源。 该 API 将生成一个 DownloadItem,可通过 will-download 事件访问。

[!NOTE] 这不会执行任何与页面源相关的安全检查, 与 webContents.downloadURL 不同。

ses.createInterruptedDownload(options)

  • options Object
  • path string - 下载的绝对路径。
  • urlChain string[] - 下载的完整 URL 链。
  • mimeType string(可选)
  • offset Integer - 下载的起始范围。
  • length Integer - 下载的总长度。
  • lastModified string(可选)- Last-Modified 请求头的值。
  • eTag string(可选)- ETag 请求头的值。
  • startTime Double(可选)- 下载开始时间,以自 UNIX 纪元起的秒数表示。

允许从之前的 Session 恢复 cancelled 或 interrupted 下载。 该 API 将生成一个 DownloadItem,可通过 will-download 事件访问。该 DownloadItem 不会关联任何 WebContents, 初始状态为 interrupted。只有当在 DownloadItem 上调用 resume API 时,下载才会开始。

ses.clearAuthCache()

返回 Promise<void> - 当会话的 HTTP 身份验证缓存被清除时解析。

ses.setPreloads(preloads) 已弃用

  • preloads string[] - 预加载脚本的绝对路径数组

添加将在与此会话关联的所有 Web 内容上执行的脚本,执行时机在常规 preload 脚本运行之前。

已弃用: 使用新的 ses.registerPreloadScript API。

ses.getPreloads() 已弃用

返回 string[],即已注册的预加载脚本路径数组。

已弃用: 使用新的 ses.getPreloadScripts API。此方法仅返回 frame 上下文类型的预加载脚本路径。

ses.registerPreloadScript(script)

注册将在本会话中其关联上下文类型内执行的预加载脚本。对于 frame 上下文,它将在 WebContents 的 Web 偏好中定义的任何 preload 之前运行。

返回 string - 已注册预加载脚本的 ID。

ses.unregisterPreloadScript(id)

  • id string - 预加载脚本 ID

注销脚本。

ses.getPreloadScripts()

返回 PreloadScript[]:已注册的预加载脚本路径数组。

ses.setCodeCachePath(path)

  • path String - 用于存储来自渲染进程的 v8 生成的 JS 代码缓存的绝对路径。

设置用于存储本会话生成的 JS 代码缓存 的目录。调用此方法之前,用户无需创建该目录;如果目录不存在,运行时将创建它,否则将使用现有目录。如果无法创建目录,则不会使用代码缓存,并且运行时内部所有与代码缓存相关的操作都会静默失败。默认情况下,该目录为相应用户数据文件夹下的 Code Cache。

请注意,默认情况下代码缓存仅对 http(s) URL 启用。要为自定义协议启用代码缓存,注册协议时必须指定 codeCache: true 和 standard: true。

ses.clearCodeCaches(options)

  • options Object
  • urls String[] (可选) - 与需要移除其生成代码缓存的资源对应的 URL 数组。如果列表为空,则缓存目录中的所有条目都会被移除。

返回 Promise<void> - 当代码缓存清除操作完成时解析。

ses.getSharedDictionaryUsageInfo()

返回 Promise<SharedDictionaryUsageInfo[]> - Chromium 网络服务存储中的共享字典信息条目数组。

共享字典用于对通过线路发送的数据进行高级压缩,特别是使用 Brotli 和 ZStandard。你不需要在 Electron 中调用任何共享字典 API 来使用此高级 Web 功能,但如果调用,它们允许对解压缩期间使用的共享字典进行更深入的控制和检查。

要获取特定共享字典条目的详细信息,请调用 getSharedDictionaryInfo(options)。

ses.getSharedDictionaryInfo(options)

  • options Object
  • frameOrigin string - 请求来源帧的源。它特定于发出请求的单个帧,并由其 scheme、host 和 port 定义。实际上,它看起来像一个 URL。
  • topFrameSite string - 顶层浏览上下文(包含请求的主帧或标签页)的站点。它比 frameOrigin 粒度更粗,并聚焦于更广泛的“站点”范围。实际上,它看起来像一个 URL。

返回 Promise<SharedDictionaryInfo[]> - Chromium 网络服务存储中的共享字典信息条目数组。

要获取所有现有共享字典的信息,请调用 getSharedDictionaryUsageInfo()。

ses.clearSharedDictionaryCache()

返回 Promise<void> - 当字典缓存已在内存和磁盘上清除时解析。

ses.clearSharedDictionaryCacheForIsolationKey(options)

  • options Object
  • frameOrigin string - 请求来源帧的源。它特定于发出请求的单个帧,并由其 scheme、host 和 port 定义。实际上,它看起来像一个 URL。
  • topFrameSite string - 顶层浏览上下文(包含请求的主帧或标签页)的站点。它比 frameOrigin 粒度更粗,并聚焦于更广泛的“站点”范围。实际上,它看起来像一个 URL。

返回 Promise<void> - 当指定隔离键的字典缓存已在内存和磁盘上清除时解析。

ses.setSpellCheckerEnabled(enable)

  • enable boolean

设置是否启用内置拼写检查器。

ses.isSpellCheckerEnabled()

返回 boolean - 内置拼写检查器是否已启用。

ses.setSpellCheckerLanguages(languages)

  • languages string[] - 要为其启用拼写检查器的语言代码数组。

内置拼写检查器不会自动检测用户正在输入的语言。为了让拼写检查器正确检查单词,你必须使用语言代码数组调用此 API。你可以通过 ses.availableSpellCheckerLanguages 属性获取支持的语言代码列表。

[!NOTE] 在 macOS 上,使用操作系统拼写检查器,并会自动检测你的语言。此 API 在 macOS 上是空操作。

ses.getSpellCheckerLanguages()

返回 string[] - 拼写检查器已启用的语言代码数组。如果此列表为空,拼写检查器将回退到使用 en-US。默认情况下,启动时如果此设置为空列表,Electron 会尝试使用当前操作系统区域设置填充此设置。此设置会在重启后持久保存。

[!NOTE] 在 macOS 上,使用操作系统拼写检查器,并且它有自己的语言列表。在 macOS 上,此 API 将返回操作系统已配置的语言。

ses.setSpellCheckerDictionaryDownloadURL(url)

  • url string - Electron 用于下载 hunspell 词典的基础 URL。

默认情况下,Electron 会从 Chromium CDN 下载 hunspell 词典。 如果你想覆盖此行为,可以使用此 API 将词典下载器指向你自己托管的 hunspell 词典版本。 我们在每个发布版本中都会发布一个 hunspell_dictionaries.zip 文件,其中包含你需要在此托管的文件。

文件服务器必须不区分大小写。 如果你无法做到这一点,则必须将每个文件上传两次:一次使用 ZIP 文件中的大小写,另一次使用全小写的文件名。

如果 hunspell_dictionaries.zip 中存在的文件可通过 https://example.com/dictionaries/language-code.bdic 访问,则你应该使用 ses.setSpellCheckerDictionaryDownloadURL('https://example.com/dictionaries/') 调用此 API。 请注意末尾的斜杠。 词典的 URL 由 ${url}${filename} 组成。

[!NOTE] 在 macOS 上,使用操作系统拼写检查器,因此我们不会下载任何词典文件。此 API 在 macOS 上是空操作。

ses.listWordsInSpellCheckerDictionary()

返回 Promise<string[]> - 应用程序自定义词典中所有单词的数组。 当完整词典从磁盘加载完成时 resolve。

ses.addWordToSpellCheckerDictionary(word)

  • word string - 你要添加到词典中的单词

返回 boolean - 该单词是否成功写入自定义词典。此 API 在非持久(内存)会话中无法工作。

[!NOTE] 在 macOS 和 Windows 上,该单词还会写入操作系统自定义词典。

ses.removeWordFromSpellCheckerDictionary(word)

  • word string - 你要从词典中移除的单词

返回 boolean - 该单词是否成功从自定义词典中移除。此 API 在非持久(内存)会话中无法工作。

[!NOTE] 在 macOS 和 Windows 上,该单词还会从操作系统自定义词典中移除。

ses.loadExtension(path[, options]) Deprecated

  • path string - 包含已解压缩 Chrome 扩展的目录的路径
  • options Object(可选)
  • allowFileAccess boolean - 是否允许扩展通过 file:// 协议读取本地文件,并将内容脚本注入到 file:// 页面。例如,在 file:// URL 上加载 DevTools 扩展时需要此设置。默认为 false。

返回 Promise<Extension> - 扩展加载完成时 resolve。

如果扩展无法加载,此方法将抛出异常。如果安装扩展时存在警告(例如扩展请求了 Electron 不支持的 API),则这些警告会记录到控制台。

请注意,Electron 不支持完整的 Chrome 扩展 API 范围。有关支持内容的更多详细信息,请参阅 支持的扩展 API。

请注意,在 Electron 的早期版本中,已加载的扩展会在应用程序的后续运行中被记住。现在不再如此:如果你希望扩展被加载,必须在每次启动应用程序时调用 loadExtension。

const { app, session } = require('electron')

const path = require('node:path')

app.whenReady().then(async () => {
  await session.defaultSession.loadExtension(
    path.join(__dirname, 'react-devtools'),
    // allowFileAccess is required to load the DevTools extension on file:// URLs.
    { allowFileAccess: true }
  )
  // Note that in order to use the React DevTools extension, you'll need to
  // download and unzip a copy of the extension.
})

此 API 不支持加载打包的(.crx)扩展。

[!NOTE] 此 API 不能在 app 模块的 ready 事件发出之前调用。

[!NOTE] 不支持将扩展加载到内存(非持久)会话中,并且会抛出错误。

已弃用: 使用新的 ses.extensions.loadExtension API。

ses.removeExtension(extensionId) Deprecated

  • extensionId string - 要移除的扩展的 ID

卸载扩展。

[!NOTE] 此 API 不能在 app 模块的 ready 事件发出之前调用。

已弃用: 使用新的 ses.extensions.removeExtension API。

ses.getExtension(extensionId) Deprecated

  • extensionId string - 要查询的扩展的 ID

返回 Extension | null - 具有给定 ID 的已加载扩展。

[!NOTE] 此 API 不能在 app 模块的 ready 事件发出之前调用。

已弃用: 使用新的 ses.extensions.getExtension API。

ses.getAllExtensions() Deprecated

返回 Extension[] - 所有已加载扩展的列表。

[!NOTE] 此 API 不能在 app 模块的 ready 事件发出之前调用。

已弃用: 使用新的 ses.extensions.getAllExtensions API。

ses.getStoragePath()

返回 string | null - 此会话数据在磁盘上持久化的绝对文件系统路径。 对于内存会话,此方法返回 null。

ses.clearData([options])

  • options Object(可选)
  • dataTypes String[](可选) - 要清除的数据类型。默认情况下,这将清除所有类型的数据。这可能包括未在此明确列出的数据类型。(请参阅 Chromium 的 BrowsingDataRemover 获取完整列表。)
    • backgroundFetch - 后台获取
    • cache - 缓存(包括 cachestorage 和 shadercache)
    • cookies - Cookie
    • downloads - 下载
    • fileSystems - 文件系统
    • indexedDB - IndexedDB
    • localStorage - 本地存储
    • serviceWorkers - Service Worker
    • webSQL - WebSQL
  • origins String[](可选) - 仅清除这些源的数据。不能与 excludeOrigins 一起使用。
  • excludeOrigins String[](可选) - 清除除这些源之外的所有源的数据。不能与 origins 一起使用。
  • avoidClosingConnections boolean(可选) - 跳过删除会关闭当前网络连接的那些 Cookie。(默认:false)
  • originMatchingMode String(可选) - 将数据匹配到源的行为。
    • third-parties-included(默认) - 存储在一方上下文中按源匹配,在第三方上下文中按顶级站点匹配。
    • origin-in-all-contexts - 存储在所有上下文中仅按源匹配。

返回 Promise<void> - 当所有数据清除完成时解析。

清除各种不同类型的数据。

此方法清除的数据类型更多,并且比 clearStorageData 方法更彻底。

[!NOTE] Cookie 的存储范围比源更广。在删除 Cookie 并按 origins(或 excludeOrigins)过滤时,Cookie 将在可注册域名级别被删除。例如,清除源 https://really.specific.origin.example.com/ 的 Cookie 最终会清除 example.com 的所有 Cookie。清除源 https://my.website.example.co.uk/ 的 Cookie 最终会清除 example.co.uk 的所有 Cookie。

[!NOTE] 清除缓存数据也会清除共享字典缓存。这意味着用于压缩的任何字典在清除缓存后可能会被重新加载。如果你希望清除共享字典缓存但保留其他缓存数据不变,可以考虑使用 clearSharedDictionaryCache 方法。

有关更多信息,请参阅 Chromium 的 BrowsingDataRemover 接口。

ses.registerLocalAIHandler(handler) 实验性

注册一个本地 AI 处理程序 UtilityProcess。若要清除处理程序,请调用 registerLocalAIHandler(null),这将断开任何现有的 Prompt API 会话并销毁任何 LanguageModelUtility 实例。

实例属性

以下属性可用于 Session 实例:

ses.availableSpellCheckerLanguages 只读

一个 string[] 数组,包含所有已知可用的拼写检查语言。向 setSpellCheckerLanguages API 提供不在此数组中的语言代码将导致错误。

ses.spellCheckerEnabled

一个 boolean,指示是否启用内置拼写检查器。

ses.storagePath 只读

一个 string | null,指示此会话的数据在磁盘上持久化的绝对文件系统路径。对于内存会话,此值返回 null。

ses.cookies 只读

此会话的 Cookies 对象。

ses.extensions 只读

此会话的 Extensions 对象。

ses.serviceWorkers 只读

此会话的 ServiceWorkers 对象。

ses.webRequest 只读

此会话的 WebRequest 对象。

ses.protocol 只读

此会话的 Protocol 对象。

const { app, session } = require('electron')

const path = require('node:path')

app.whenReady().then(() => {
  const protocol = session.fromPartition('some-partition').protocol
  if (!protocol.registerFileProtocol('atom', (request, callback) => {
    const url = request.url.substr(7)
    callback({ path: path.normalize(path.join(__dirname, url)) })
  })) {
    console.error('Failed to register protocol')
  }
})

ses.netLog 只读

此会话的 NetLog 对象。

const { app, session } = require('electron')

app.whenReady().then(async () => {
  const netLog = session.fromPartition('some-partition').netLog
  netLog.startLogging('/path/to/net-log')
  // After some network events
  const path = await netLog.stopLogging()
  console.log('Net-logs written to', path)
})

本页原文 Markdown:在 AtomGit 查看·内容源自开源项目 el/electron