跳转到主要内容

session

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

进程: 主进程

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

还可以通过使用 WebContentssession 属性,或从 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 Object (可选)

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

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

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

session.fromPath(path[, options])

  • path string
  • options Object (可选)

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

要使用 options 创建 Session,必须确保具有 pathSession 之前从未被使用过。无法更改现有 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'

返回

当 Electron 准备在 webContents 中下载 item 时发出。

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

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 加载的扩展程序。
  • 重新加载扩展程序

事件: 'extension-unloaded'

返回

在卸载扩展程序后发出。当调用 Session.removeExtension 时会发生此情况。

事件: 'extension-ready'

返回

在加载扩展程序并初始化支持扩展程序后台页面启动所需的所有浏览器状态后发出。

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

返回

  • event Event
  • details Object
    • origin 字符串 - 发起对被阻止路径的访问的源。
    • isDirectory 布尔值 - 路径是否为目录。
    • path 字符串 - 尝试访问的被阻止路径。
  • callback Function
    • action 字符串 - 作为受限路径访问尝试结果而要采取的操作。
      • allow - 这将允许访问 path,尽管状态受限。
      • deny - 这将阻止访问请求并触发 AbortError
      • tryAgain - 这将打开一个新的文件选择器,并允许用户选择另一个路径。
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'

返回

  • event Event
  • preconnectUrl 字符串 - 渲染器请求预连接的 URL。
  • allowCredentials 布尔值 - 如果渲染器请求连接包含凭据(有关更多详细信息,请参阅 规范)。

当渲染进程请求预连接到 URL 时发出,通常是由于 资源提示

事件: 'spellcheck-dictionary-initialized'

返回

  • event Event
  • languageCode 字符串 - 字典文件的语言代码

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

事件: 'spellcheck-dictionary-download-begin'

返回

  • event Event
  • languageCode 字符串 - 字典文件的语言代码

在 hunspell 字典文件开始下载时发出

事件: 'spellcheck-dictionary-download-success'

返回

  • event Event
  • languageCode 字符串 - 字典文件的语言代码

在 hunspell 字典文件成功下载后发出

事件: 'spellcheck-dictionary-download-failure'

返回

  • event Event
  • languageCode 字符串 - 字典文件的语言代码

在 hunspell 字典文件下载失败时发出。有关失败的详细信息,您应该收集 netlog 并检查下载请求。

事件: 'select-hid-device'

返回

  • event Event
  • details Object
    • deviceList HIDDevice[]
    • frame WebFrameMain | null - 发起此事件的框架。如果框架已导航或销毁,则可能为 null
  • callback Function
    • deviceId 字符串 | null (可选)

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

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 Event
  • details Object
    • device HIDDevice
    • frame WebFrameMain | null - 发起此事件的框架。如果框架已导航或销毁,则可能为 null

在调用 navigator.hid.requestDevice 并且 select-hid-device 触发后发出,如果设备在 select-hid-device 的回调被调用之前被删除。当使用 UI 来要求用户选择设备时,此事件用于更新 UI 以删除指定的设备。

事件: 'hid-device-revoked'

返回

  • event Event
  • details Object
    • device HIDDevice
    • origin 字符串 (可选) - 撤销设备的源。

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

事件: 'select-serial-port'

返回

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

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'

返回

在调用 navigator.serial.requestPortselect-serial-port 事件触发后,如果新的串口在 select-serial-port 回调函数被调用之前变为可用,则会发出此事件。当使用 UI 提示用户选择端口时,可以使用此事件来更新 UI 以显示新添加的端口。

事件: 'serial-port-removed'

返回

在调用 navigator.serial.requestPortselect-serial-port 事件触发后,如果串口在 select-serial-port 回调函数被调用之前被移除,则会发出此事件。当使用 UI 提示用户选择端口时,可以使用此事件来更新 UI 以移除指定的端口。

事件: 'serial-port-revoked'

返回

  • event Event
  • details Object
    • port SerialPort
    • frame WebFrameMain | null - 发起此事件的框架。如果框架已导航或销毁,则可能为 null
    • origin 字符串 - 撤销设备来源。

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

// 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}`)
})
})
// 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 Event
  • details Object
    • deviceList USBDevice[]
    • frame WebFrameMain | null - 发起此事件的框架。如果框架已导航或销毁,则可能为 null
  • callback Function
    • deviceId 字符串 (可选)

当对 navigator.usb.requestDevice 进行调用时,需要选择 USB 设备时发出。应使用 deviceId 调用 callback 以进行选择;不向 callback 传递任何参数将取消请求。此外,可以通过使用 ses.setPermissionCheckHandler(handler)ses.setDevicePermissionHandler(handler) 来进一步管理 navigator.usb 上的权限。

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.requestDeviceselect-usb-device 事件触发后,如果新的设备在 select-usb-device 回调函数被调用之前变为可用,则会发出此事件。当使用 UI 提示用户选择设备时,可以使用此事件来更新 UI 以显示新添加的设备。

事件: 'usb-device-removed'

返回

在调用 navigator.usb.requestDeviceselect-usb-device 事件触发后,如果设备在 select-usb-device 回调函数被调用之前被移除,则会发出此事件。当使用 UI 提示用户选择设备时,可以使用此事件来更新 UI 以移除指定的设备。

事件: 'usb-device-revoked'

返回

  • event Event
  • details Object
    • device USBDevice
    • origin 字符串 (可选) - 撤销设备的源。

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

实例方法

以下方法可在 Session 的实例上使用

ses.getCacheSize()

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

ses.clearCache()

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

清除会话的 HTTP 缓存。

ses.clearStorageData([options])

  • options Object (可选)
    • origin 字符串 (可选) - 应遵循 window.location.origin 的表示形式 scheme://host:port
    • storages 字符串[] (可选) - 要清除的存储类型,可以是 cookiesfilesystemindexdblocalstorageshadercachewebsqlserviceworkerscachestorage。如果未指定,则清除所有存储类型。
    • quotas 字符串[] (可选) - 要清除的配额类型,可以是 temporary。如果未指定,则清除所有配额。

返回 Promise<void> - 在存储数据清除后解析。

ses.flushStorageData()

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

ses.setProxy(config)

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

设置代理设置。

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

ses.resolveHost(host, [options])

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

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

ses.resolveProxy(url)

  • url URL

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

ses.forceReloadProxyConfig()

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

ses.setDownloadPath(path)

  • path 字符串 - 下载位置。

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

ses.enableNetworkEmulation(options)

  • options Object
    • offline 布尔值 (可选) - 是否模拟网络中断。默认为 false。
    • latency Double (可选) - 往返时间,以毫秒为单位。默认为 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 字符串 - 要预连接的 URL。仅 origin 与打开套接字相关。
    • numSockets 数字 (可选) - 要预连接的套接字数量。必须在 1 到 6 之间。默认为 1。

预连接到 origin 的给定数量的套接字。

ses.closeAllConnections()

返回 Promise<void> - 在关闭所有连接后解析。

注意

它将终止 / 失败当前正在进行的请求。

ses.fetch(input[, init])

返回 Promise<GlobalResponse> - 参见 Response

发送一个请求,类似于渲染器中的 fetch() 工作方式,使用 Chrome 的网络堆栈。这与 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(),这是一种便捷方法,可以从 默认会话 发出请求。

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

限制

  • 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 函数 | null
    • request 对象
      • hostname 字符串
      • certificate Certificate
      • validatedCertificate Certificate
      • isIssuedByKnownRoot 布尔值 - 如果 Chromium 识别根 CA 为标准根,则为 true。如果不是,则可能是此证书是由 MITM 代理生成的,其根已在本地安装(例如,由公司代理安装)。如果 verificationResult 不是 OK,则不应信任此证书。
      • verificationResult 字符串 - 如果证书受信任,则为 OK,否则为 CERT_REVOKED 等错误。
      • errorCode 整数 - 错误代码。
    • callback Function
      • verificationResult 整数 - 值可以是来自 此处 的证书错误代码之一。除了证书错误代码外,还可以使用以下特殊代码。
        • 0 - 表示成功并禁用证书透明度验证。
        • -2 - 表示失败。
        • -3 - 使用 chromium 的验证结果。

设置 session 的证书验证过程,每当请求服务器证书验证时,都会使用 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 函数 | null
    • webContents WebContents - 请求权限的 WebContents。请注意,如果请求来自子框架,您应该使用 requestingUrl 来检查请求来源。
    • permission 字符串 - 请求的权限类型。
      • clipboard-read - 请求访问从剪贴板读取。
      • clipboard-sanitized-write - 请求访问写入剪贴板。
      • display-capture - 请求访问通过 屏幕捕获 API 捕获屏幕。
      • fullscreen - 请求通过 全屏 API 控制应用程序的全屏状态。
      • geolocation - 请求通过 地理位置 API 访问用户的地理位置
      • idle-detection - 请求通过 IdleDetector API 访问用户的空闲状态。
      • media - 请求访问媒体设备,例如摄像头、麦克风和扬声器。
      • mediaKeySystem - 请求访问受 DRM 保护的内容。
      • midi - 请求在 Web MIDI API 中访问 MIDI。
      • midiSysex - 请求在 Web MIDI API 中使用系统独占消息。
      • notifications - 请求创建通知并使用 通知 API 在用户的系统托盘中显示它们
      • pointerLock - 请求通过 指针锁定 API 直接解释鼠标移动作为输入方法。这些请求始终似乎来自主框架。
      • keyboardLock - 请求通过 键盘锁定 API 捕获物理键盘上任何或所有按键的按键。这些请求始终似乎来自主框架。
      • openExternal - 请求在外部应用程序中打开链接。
      • speaker-selection - 请求通过 speaker-selection 权限策略 枚举和选择音频输出设备。
      • storage-access - 允许在第三方上下文中加载的内容使用 存储访问 API 请求访问第三方 Cookie。
      • top-level-storage-access - 允许顶级站点代表源自同一相关网站集的另一个站点的嵌入式内容请求第三方 Cookie 访问权限,使用 存储访问 API
      • window-management - 请求使用 getScreenDetails API 枚举屏幕。
      • unknown - 一个未识别的权限请求。
      • fileSystem - 请求使用 文件系统 API 访问读取、写入和文件管理功能。
    • callback Function
      • permissionGranted 布尔值 - 允许或拒绝权限。
    • 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)
})

ses.setPermissionCheckHandler(handler)

  • handler 函数<布尔值> | null
    • webContents (WebContents | null) - 检查权限的 WebContents。请注意,如果请求来自子框架,您应该使用 requestingUrl 来检查请求来源。所有进行权限检查的跨域子框架都会将 null webContents 传递给此处理程序,而某些其他权限检查(例如 notifications 检查)始终会传递 null。您应该使用 embeddingOriginrequestingOrigin 来确定拥有框架和请求框架分别位于哪个来源。
    • permission 字符串 - 权限检查类型。
      • clipboard-read - 请求访问从剪贴板读取。
      • clipboard-sanitized-write - 请求访问写入剪贴板。
      • geolocation - 通过 地理位置 API 访问用户的地理位置数据
      • fullscreen - 通过 全屏 API 控制应用程序的全屏状态。
      • hid - 通过 WebHID API 访问 HID 协议以操作 HID 设备。
      • idle-detection - 通过 IdleDetector API 访问用户的空闲状态。
      • media - 访问媒体设备,例如摄像头、麦克风和扬声器。
      • mediaKeySystem - 访问受 DRM 保护的内容。
      • midi - 在 Web MIDI API 中启用 MIDI 访问。
      • midiSysex - 在 Web MIDI API 中使用系统独占消息。
      • notifications - 使用 通知 API 向用户配置和显示桌面通知。
      • openExternal - 在外部应用程序中打开链接。
      • pointerLock - 通过 指针锁定 API 直接解释鼠标移动作为输入方法。这些请求始终似乎来自主框架。
      • serial - 使用 Web Serial API 从串行设备读取和写入。
      • storage-access - 允许在第三方上下文中加载的内容使用 存储访问 API 请求访问第三方 Cookie。
      • top-level-storage-access - 允许顶级站点代表源自同一相关网站集的另一个站点的嵌入式内容请求第三方 Cookie 访问权限,使用 存储访问 API
      • usb - 使用 WebUSB API 向 Web 公开非标准通用串行总线 (USB) 兼容设备服务。
      • deprecated-sync-clipboard-read 已弃用 - 请求访问运行 document.execCommand("paste")
      • fileSystem - 请求使用 文件系统 API 访问读取、写入和文件管理功能。
    • requestingOrigin 字符串 - 权限检查的来源 URL
    • details 对象 - 某些属性仅在某些权限类型上可用。
      • embeddingOrigin 字符串 (可选) - 嵌入进行权限检查的框架的来源。仅针对进行权限检查的跨域子框架设置。
      • securityOrigin 字符串 (可选) - media 检查的安全来源。
      • mediaType 字符串 (可选) - 请求的媒体类型,可以是 videoaudiounknown
      • requestingUrl 字符串 (可选) - 请求框架加载的最后一个 URL。不提供给进行权限检查的跨域子框架。
      • isMainFrame 布尔值 - 发出请求的框架是否为主框架。
      • filePath string (optional) - 文件系统请求的路径。
      • isDirectory boolean (optional) - 文件系统请求是否是一个目录。
      • fileAccessType string (optional) - 文件系统请求的访问类型。可以是 writablereadable

设置处理程序,该处理程序可用于响应会话的权限检查。返回 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
})
注意

由于 Chromium 的限制,fileSystem 请求的 isMainFrame 始终为 false

ses.setDisplayMediaRequestHandler(handler[, opts])

  • handler 函数 | null
    • request 对象
      • frame WebFrameMain | null - 请求访问媒体的框架。如果框架已导航或被销毁,则可能为 null
      • securityOrigin String - 发出请求的页面的来源。
      • videoRequested Boolean - 如果 Web 内容请求了视频流,则为 true。
      • audioRequested Boolean - 如果 Web 内容请求了音频流,则为 true。
      • userGesture Boolean - 此请求触发时是否处于用户手势活动状态。
    • callback Function
      • streams Object
        • video Object | WebFrameMain (optional)
        • audio String | WebFrameMain (optional) - 如果指定了字符串,可以是 loopbackloopbackWithMute。指定回环设备将捕获系统音频,目前仅在 Windows 上受支持。如果指定了 WebFrameMain,将从该框架捕获音频。
        • enableLocalEcho Boolean (optional) - 如果 audioWebFrameMain 并且将其设置为 true,则本地音频播放将不会被静音(例如,使用 MediaRecorder 录制 WebFrameMain 并将此标志设置为 true 将允许音频传递到扬声器进行录制)。默认值为 false
  • opts Object (optional) macOS Experimental
    • useSystemPicker Boolean - 如果应使用可用的本机系统选择器,则为 true。默认值为 falsemacOS Experimental

当 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 对象作为视频或音频流传递将捕获该框架的视频或音频流。

const { session } = require('electron')

session.defaultSession.setDisplayMediaRequestHandler((request, callback) => {
// Allow the tab to capture itself.
callback({ video: request.frame })
})

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

ses.setDevicePermissionHandler(handler)

  • handler 函数<布尔值> | null
    • details Object
      • deviceType string - 正在请求权限的设备类型,可以是 hidserialusb
      • origin string - 发出权限检查的页面的来源 URL。
      • device HIDDevice | SerialPort | USBDevice - 正在请求权限的设备。

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

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)

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

设置处理程序,该处理程序可用于覆盖哪些 USB 类是受保护的。处理程序的返回值是应视为受保护的 USB 类字符串数组(例如,在渲染器中不可用)。数组的有效值是

  • audio
  • audio-video
  • hid
  • mass-storage
  • smart-card
  • video
  • wireless

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

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 函数 | null
    • details Object
      • deviceId 字符串
      • pairingKind string - 正在请求的配对提示类型。以下值之一
        • confirm 此提示正在请求确认是否应配对蓝牙设备。
        • confirmPin 此提示正在请求确认提供的 PIN 是否与设备上显示的 PIN 匹配。
        • providePin 此提示正在请求为设备提供 PIN。
      • frame WebFrameMain | null - 发起此处理程序的框架。如果框架已导航或被销毁,则可能为 null
      • pin string (optional) - 如果 pairingKindconfirmPin,则为要验证的 PIN 值。
    • callback Function
      • response Object
        • confirmed boolean - 如果对话框被取消,应传递 false。如果 pairingKindconfirmconfirmPin,则此值应指示是否确认配对。如果 pairingKindprovidePin,则当提供值时,该值应为 true
        • pin string | null (optional) - 当 pairingKindprovidePin 时,此值应为蓝牙设备所需的 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 a 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 (optional)

覆盖此会话的 userAgentacceptLanguages

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 (optional) - 可以是 tls1tls1.1tls1.2tls1.3。连接到远程服务器时允许的最小 SSL 版本。默认值为 tls1
    • maxVersion string (optional) - 可以是 tls1.2tls1.3。连接到远程服务器时允许的最大 SSL 版本。默认值为 tls1.3
    • disabledCipherSuites Integer[] (optional) - 除了 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 事件访问。

注意

这不会执行与页面来源相关的任何安全检查,与 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 中恢复 cancelledinterrupted 下载。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 偏好设置中定义的任何预加载之前运行。

返回 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: truestandard: 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 - 请求发起的框架的来源。 它特定于发出请求的单个框架,由其方案、主机和端口定义。 在实践中,看起来像一个 URL。
    • topFrameSite string - 顶级浏览上下文(包含请求的主框架或选项卡)的站点。 它比 frameOrigin 粒度更粗,侧重于更广泛的“站点”范围。 在实践中,看起来像一个 URL。

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

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

ses.clearSharedDictionaryCache()

返回 Promise<void> - 在清除字典缓存(内存和磁盘)后解析。

ses.clearSharedDictionaryCacheForIsolationKey(options)

  • options Object
    • frameOrigin string - 请求发起的框架的来源。 它特定于发出请求的单个框架,由其方案、主机和端口定义。 在实践中,看起来像一个 URL。
    • topFrameSite string - 顶级浏览上下文(包含请求的主框架或选项卡)的站点。 它比 frameOrigin 粒度更粗,侧重于更广泛的“站点”范围。 在实践中,看起来像一个 URL。

返回 Promise<void> - 在清除指定隔离密钥的字典缓存(内存和磁盘)后解析。

ses.setSpellCheckerEnabled(enable)

  • enable boolean

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

ses.isSpellCheckerEnabled()

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

ses.setSpellCheckerLanguages(languages)

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

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

注意

在 macOS 上,使用操作系统拼写检查器并会自动检测您的语言。 此 API 在 macOS 上不起作用。

ses.getSpellCheckerLanguages()

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

注意

在 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}

注意

在 macOS 上,使用操作系统拼写检查器,因此我们不会下载任何字典文件。 此 API 在 macOS 上不起作用。

ses.listWordsInSpellCheckerDictionary()

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

ses.addWordToSpellCheckerDictionary(word)

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

返回 boolean - 单词是否已成功写入自定义字典。 此 API 不适用于非持久性(内存中)会话。

注意

在 macOS 和 Windows 上,此单词也将写入操作系统自定义字典。

ses.removeWordFromSpellCheckerDictionary(word)

  • word string - 您要从字典中删除的单词

返回 boolean - 单词是否已成功从自定义字典中删除。 此 API 不适用于非持久性(内存中)会话。

注意

在 macOS 和 Windows 上,此单词也将从操作系统自定义字典中删除。

ses.loadExtension(path[, options]) 已弃用

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

返回 Promise<Extension> - 在扩展程序加载后解析。

如果扩展程序无法加载,此方法将引发异常。如果扩展程序安装时存在警告(例如,如果扩展程序请求 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) 扩展程序。

注意

app 模块发出 ready 事件之前,无法调用此 API。

注意

不支持将扩展程序加载到内存中(非持久性)会话中,并且会抛出错误。

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

ses.removeExtension(extensionId) 已弃用

  • extensionId string - 要删除的扩展程序的 ID

卸载一个扩展程序。

注意

app 模块发出 ready 事件之前,无法调用此 API。

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

ses.getExtension(extensionId) 已弃用

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

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

注意

app 模块发出 ready 事件之前,无法调用此 API。

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

ses.getAllExtensions() 已弃用

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

注意

app 模块发出 ready 事件之前,无法调用此 API。

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

ses.getStoragePath()

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

ses.clearData([options])

  • options Object (可选)
    • dataTypes String[] (可选) - 要清除的数据类型。默认情况下,这将清除所有类型的数据。这可能包括此处未明确列出的数据类型。(请参阅 Chromium 的 BrowsingDataRemover 以获取完整的列表。)
      • backgroundFetch - 后台获取
      • cache - 缓存(包括 cachestorageshadercache
      • 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 方法更彻底。

注意

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

注意

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

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

实例属性

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)
})