跳到主要内容

session

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

进程:主进程

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 对象 (可选)

返回 Session - 来自 partition 字符串的 session 实例。当存在具有相同 partition 的现有 Session 时,将返回该实例;否则将使用 options 创建新的 Session 实例。

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

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

session.fromPath(path[, options])

  • path 字符串
  • options 对象 (可选)

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

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

属性

session 模块具有以下属性

session.defaultSession

一个 Session 对象,应用程序的默认会话对象。

类: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() 将取消下载,并且在进程的下一个 tick 中 item 将不可用。

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 事件
  • details 对象
    • origin 字符串 - 启动对被阻止路径访问的来源。
    • isDirectory boolean - 路径是否为目录。
    • path 字符串 - 尝试访问的被阻止路径。
  • callback 函数
    • 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 事件
  • preconnectUrl 字符串 - 渲染器请求预连接的 URL。
  • allowCredentials boolean - 如果渲染器请求连接包含凭据,则为 True(有关更多详细信息,请参阅 规范)。

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

事件:'spellcheck-dictionary-initialized'

返回

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

当 hunspell 字典文件成功初始化时触发。 这在文件下载后发生。

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

返回

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

当 hunspell 字典文件开始下载时触发

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

返回

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

当 hunspell 字典文件成功下载时触发

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

返回

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

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

事件:'select-hid-device'

返回

  • event 事件
  • details 对象
    • deviceList HIDDevice[]
    • frame WebFrameMain | null - 启动此事件的 frame。 如果在 frame 导航或销毁后访问,则可能为 null
  • callback 函数
    • deviceId string | 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 事件
  • details 对象
    • device HIDDevice
    • frame WebFrameMain | null - 启动此事件的 frame。 如果在 frame 导航或销毁后访问,则可能为 null

在调用 navigator.hid.requestDevice 并且 select-hid-device 已触发后触发,如果在从 select-hid-device 调用回调之前有新设备可用。 此事件旨在用于在使用 UI 要求用户选择设备时,以便可以使用新添加的设备更新 UI。

事件:'hid-device-removed'

返回

  • event 事件
  • details 对象
    • device HIDDevice
    • frame WebFrameMain | null - 启动此事件的 frame。 如果在 frame 导航或销毁后访问,则可能为 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 传递空字符串将取消请求。 此外,可以使用带有 serial 权限的 ses.setPermissionCheckHandler(handler) 来管理 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.requestPort 并且 select-serial-port 已触发后触发,如果在从 select-serial-port 调用回调之前有新的串行端口可用。 此事件旨在用于在使用 UI 要求用户选择端口时,以便可以使用新添加的端口更新 UI。

事件:'serial-port-removed'

返回

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

事件:'serial-port-revoked'

返回

  • event 事件
  • details 对象
    • port SerialPort
    • frame WebFrameMain | null - 启动此事件的 frame。 如果在 frame 导航或销毁后访问,则可能为 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 事件
  • details 对象
    • deviceList USBDevice[]
    • frame WebFrameMain | null - 启动此事件的 frame。 如果在 frame 导航或销毁后访问,则可能为 null
  • callback 函数
    • 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.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 事件
  • details 对象
    • device USBDevice
    • origin 字符串 (可选) - 设备已被撤销的来源。

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

实例方法

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

ses.getCacheSize()

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

ses.clearCache()

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

清除会话的 HTTP 缓存。

ses.clearStorageData([options])

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

返回 Promise<void> - 当存储数据已清除时 resolve。

ses.flushStorageData()

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

ses.setProxy(config)

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

设置代理设置。

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

ses.resolveHost(host, [options])

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

返回 Promise<ResolvedHost> - 使用 host 的已解析 IP 地址进行 Resolve。

ses.resolveProxy(url)

  • url URL

返回 Promise<string> - 使用 url 的代理信息进行 Resolve。

ses.forceReloadProxyConfig()

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

ses.setDownloadPath(path)

  • path 字符串 - 下载位置。

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

ses.enableNetworkEmulation(options)

  • options 对象
    • 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 对象
    • url 字符串 - 预连接的 URL。 只有来源与打开套接字相关。
    • numSockets number (可选) - 要预连接的套接字数。 必须介于 1 和 6 之间。 默认为 1。

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

ses.closeAllConnections()

返回 Promise<void> - 当所有连接都关闭时 Resolve。

注意: 这将终止/失败当前正在进行的所有请求。

ses.fetch(input[, init])

返回 Promise<GlobalResponse> - 请参阅 Response

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

有关更多详细信息,请参阅 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 boolean - 如果 Chromium 将根 CA 识别为标准根,则为 true。 如果不是,则可能是此证书是由 MITM 代理生成的,该代理的根已本地安装(例如,通过公司代理)。 如果 verificationResult 不是 OK,则不应信任此证书。
      • verificationResult string - 如果证书受信任,则为 OK,否则为 CERT_REVOKED 等错误。
      • errorCode Integer - 错误代码。
    • callback 函数
      • verificationResult Integer - 值可以是来自 此处 的证书错误代码之一。 除了证书错误代码之外,还可以使用以下特殊代码。
        • 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 - 请求通过 Screen Capture API 捕获屏幕的权限。
      • fullscreen - 请求通过 Fullscreen API 控制应用程序全屏状态的权限。
      • geolocation - 请求通过 Geolocation API 访问用户位置的权限
      • idle-detection - 请求通过 IdleDetector API 访问用户空闲状态的权限。
      • media - 请求访问媒体设备,如摄像头、麦克风和扬声器。
      • mediaKeySystem - 请求访问受 DRM 保护的内容。
      • midi - 在 Web MIDI API 中请求 MIDI 访问权限。
      • midiSysex - 在 Web MIDI API 中请求使用系统独占消息。
      • notifications - 请求创建通知以及使用 Notifications API 在用户系统托盘中显示通知的能力。
      • pointerLock - 请求通过 Pointer Lock API 直接将鼠标移动解释为输入方式。这些请求始终显示为源自主框架。
      • keyboardLock - 请求通过 Keyboard Lock API 捕获物理键盘上任何或所有键的按键。这些请求始终显示为源自主框架。
      • openExternal - 请求在外部应用程序中打开链接。
      • speaker-selection - 请求通过 speaker-selection 权限策略 枚举和选择音频输出设备。
      • storage-access - 允许在第三方上下文中加载的内容使用 Storage Access API 请求访问第三方 Cookie。
      • top-level-storage-access - 允许顶级站点代表来自同一相关网站集中另一个站点的嵌入内容,使用 Storage Access API 请求第三方 Cookie 访问权限。
      • window-management - 请求使用 getScreenDetails API 访问枚举屏幕。
      • unknown - 未识别的权限请求。
      • fileSystem - 请求使用 File System API 访问读取、写入和文件管理功能。
    • callback 函数
      • 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)
})

ses.setPermissionCheckHandler(handler)

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

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

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

return false // denied
})

ses.setDisplayMediaRequestHandler(handler[, opts])

  • handler 函数 | null
    • request 对象
      • frame WebFrameMain | null - 请求访问媒体的框架。如果在框架导航或销毁后访问,则可能为 null
      • securityOrigin String - 发出请求的页面的来源。
      • videoRequested Boolean - 如果 Web 内容请求了视频流,则为 true。
      • audioRequested Boolean - 如果 Web 内容请求了音频流,则为 true。
      • userGesture Boolean - 触发此请求时,用户手势是否处于活动状态。
    • callback 函数
      • 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 Function<boolean> | null
    • details 对象
      • deviceType string - 正在请求权限的设备类型,可以是 hidserialusb
      • origin string - 设备权限检查的来源 URL。
      • device HIDDevice | SerialPort | USBDevice - 正在为其请求权限的设备。

设置可用于响应 session 的设备权限检查的处理程序。返回 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 对象
      • 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 对象
      • deviceId string
      • pairingKind string - 请求的配对提示类型。以下值之一
        • confirm 此提示请求确认是否应配对蓝牙设备。
        • confirmPin 此提示请求确认提供的 PIN 码与设备上显示的 PIN 码是否匹配。
        • providePin 此提示请求为设备提供 PIN 码。
      • frame WebFrameMain | null - 启动此处理程序的框架。如果在框架导航或销毁后访问,则可能为 null
      • pin string (optional) - 如果 pairingKindconfirmPin,则为要验证的 PIN 码值。
    • callback 函数
      • 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 或协商身份验证发送凭据。

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) - 除了网络内置策略禁用的密码套件之外,应显式阻止使用的密码套件列表。支持的文字形式: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 对象 (可选)
    • headers Record<string, string> (optional) - HTTP 请求标头。

启动下载 url 处的资源。API 将生成一个 DownloadItem,可以使用 will-download 事件访问该项目。

注意:webContents.downloadURL 不同,这不会执行任何与页面来源相关的安全检查。

ses.createInterruptedDownload(options)

  • options 对象
    • path string - 下载的绝对路径。
    • urlChain string[] - 下载的完整 URL 链。
    • mimeType string (optional)
    • offset Integer - 下载的起始范围。
    • length Integer - 下载的总长度。
    • lastModified string (optional) - Last-Modified 标头值。
    • eTag string (optional) - ETag 标头值。
    • startTime Double (optional) - 下载开始时间,以自 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 对象
    • urls String[] (optional) - 与需要删除其生成的代码缓存的资源对应的 URL 数组。如果列表为空,则将删除缓存目录中的所有条目。

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

ses.getSharedDictionaryUsageInfo()

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

共享字典用于增强通过网络发送的数据的高级压缩,特别是使用 Brotli 和 ZStandard。您无需调用 Electron 中的任何共享字典 API 即可使用此高级 Web 功能,但如果调用,它们允许更深入地控制和检查解压缩期间使用的共享字典。

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

ses.getSharedDictionaryInfo(options)

  • options 对象
    • frameOrigin string - 请求源自的框架的来源。它特定于发出请求的单个框架,并由其方案、主机和端口定义。在实践中,看起来像一个 URL。
    • topFrameSite string - 顶级浏览上下文(包含请求的主框架或标签页)的站点。它不如 frameOrigin 精细,而是侧重于更广泛的“站点”范围。在实践中,看起来像一个 URL。

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

要获取有关所有当前共享字典的信息,请调用 getSharedDictionaryUsageInfo()

ses.clearSharedDictionaryCache()

返回 Promise<void> - 当字典缓存已清除(包括内存和磁盘)时解析。

ses.clearSharedDictionaryCacheForIsolationKey(options)

  • options 对象
    • 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 10 上,此单词也将被写入操作系统自定义字典

ses.removeWordFromSpellCheckerDictionary(word)

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

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

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

ses.loadExtension(path[, options])

  • path string - 包含未打包的 Chrome 扩展程序的目录路径
  • options 对象 (可选)
    • 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) 扩展程序。

注意: 此 API 无法在 app 模块的 ready 事件发出之前调用。

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

ses.removeExtension(extensionId)

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

卸载扩展程序。

注意: 此 API 无法在 app 模块的 ready 事件发出之前调用。

ses.getExtension(extensionId)

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

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

注意: 此 API 无法在 app 模块的 ready 事件发出之前调用。

ses.getAllExtensions()

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

注意: 此 API 无法在 app 模块的 ready 事件发出之前调用。

ses.getStoragePath()

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

ses.clearData([options])

  • options 对象 (可选)
    • dataTypes String[] (可选) - 要清除的数据类型。 默认情况下,这将清除所有类型的数据。 这可能包括此处未明确列出的数据类型。(有关完整列表,请参阅 Chromium 的 BrowsingDataRemover。)
      • backgroundFetch - 后台获取
      • cache - 缓存(包括 cachestorageshadercache
      • cookies - Cookie
      • downloads - 下载
      • fileSystems - 文件系统
      • indexedDB - IndexedDB
      • localStorage - 本地存储
      • serviceWorkers - Service Workers
      • 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 的存储范围比来源更广。当删除 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。

注意: 清除缓存数据也会清除共享字典缓存。 这意味着用于压缩的任何字典都可能在清除缓存后重新加载。 如果您希望清除共享字典缓存,但保持其他缓存数据完整,您可能需要使用 clearSharedDictionaryCache 方法。

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

实例属性

以下属性在 Session 的实例上可用

ses.availableSpellCheckerLanguages 只读

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

ses.spellCheckerEnabled

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

ses.storagePath 只读

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

ses.cookies 只读

此会话的 Cookies 对象。

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