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
string
返回 Session
- 从 partition
字符串获得的会话实例。 当存在具有相同 partition
的现有 Session
时,将返回它;否则将使用 options
创建新的 Session
实例。
如果 partition
以 persist:
开头,则页面将使用对应用程序中所有具有相同 partition
的页面可用的持久会话。 如果没有 persist:
前缀,则页面将使用内存中会话。 如果 partition
为空,则将返回应用程序的默认会话。
要使用 options
创建 Session
,您必须确保具有 partition
的 Session
以前从未使用过。 无法更改现有 Session
对象的 options
。
session.fromPath(path[, options])
path
string
返回 Session
- 一个会话实例,其绝对路径由 path
字符串指定。 当存在具有相同绝对路径的现有 Session
时,它将被返回;否则将使用 options
创建新的 Session
实例。 如果路径不是绝对路径,则调用将抛出错误。 此外,如果提供了空字符串,也将抛出错误。
要使用 options
创建 Session
,您必须确保具有 path
的 Session
以前从未使用过。 无法更改现有 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'
返回
event
Eventitem
DownloadItemwebContents
WebContents
当 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'
返回
event
Eventextension
Extension
扩展加载后发出。 每当扩展被添加到“已启用”扩展集时,就会发生这种情况。 这包括:
- 从
Session.loadExtension
加载的扩展。 - 从崩溃中重新加载的扩展。
- 如果扩展请求重新加载(
chrome.runtime.reload()
)。 - 如果扩展程序请求了它 (
chrome.runtime.reload()
)。
- 如果扩展请求重新加载(
事件:'extension-unloaded'
返回
event
Eventextension
Extension
扩展卸载后发出。 这在调用 Session.removeExtension
时发生。
事件:'extension-ready'
返回
event
Eventextension
Extension
扩展加载并初始化所有必要的浏览器状态以支持扩展后台页面的启动后发出。
事件:'file-system-access-restricted'
返回
event
Eventdetails
Objectorigin
string - 启动对受限路径访问的来源。isDirectory
boolean - 路径是否是目录。path
string - 尝试访问的受限路径。
callback
Functionaction
string - 针对受限路径访问尝试采取的行动。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
EventpreconnectUrl
string - 渲染器请求预连接的 URL。allowCredentials
boolean - 如果渲染器请求连接包含凭据 (更多详情请参见 spec),则为 true。
当渲染进程请求预连接到 URL 时发出,通常是由于 资源提示。
事件:'spellcheck-dictionary-initialized'
返回
event
EventlanguageCode
string - 字典文件的语言代码
当 hunspell 字典文件成功初始化时发出。这发生在文件下载之后。
事件:'spellcheck-dictionary-download-begin'
返回
event
EventlanguageCode
string - 字典文件的语言代码
当 hunspell 字典文件开始下载时发出
事件:'spellcheck-dictionary-download-success'
返回
event
EventlanguageCode
string - 字典文件的语言代码
当 hunspell 字典文件成功下载时发出
事件:'spellcheck-dictionary-download-failure'
返回
event
EventlanguageCode
string - 字典文件的语言代码
当 hunspell 字典文件下载失败时发出。有关失败的详细信息,您应该收集网络日志并检查下载请求。
事件:'select-hid-device'
返回
event
Eventdetails
ObjectdeviceList
HIDDevice[]frame
WebFrameMain | null - 触发此事件的帧。 如果在帧导航或销毁后访问,则可能为null
。
callback
FunctiondeviceId
string | null (可选)
当调用 navigator.hid.requestDevice
时需要选择 HID 设备时发出。 callback
应使用要选择的 deviceId
进行调用;不向 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
Eventdetails
Objectdevice
HIDDeviceframe
WebFrameMain | null - 触发此事件的帧。 如果在帧导航或销毁后访问,则可能为null
。
在调用 navigator.hid.requestDevice
并且 select-hid-device
已触发后,如果在新设备可用之前调用了 select-hid-device
的回调,则发出此事件。 此事件旨在用于使用 UI 要求用户选择设备,以便 UI 可以使用新添加的设备进行更新。
事件:'hid-device-removed'
返回
event
Eventdetails
Objectdevice
HIDDeviceframe
WebFrameMain | null - 触发此事件的帧。 如果在帧导航或销毁后访问,则可能为null
。
在调用 navigator.hid.requestDevice
并且 select-hid-device
已触发后,如果在调用 select-hid-device
的回调之前设备已被移除,则发出此事件。 此事件旨在用于使用 UI 要求用户选择设备,以便 UI 可以更新以移除指定设备。
事件:'hid-device-revoked'
返回
event
Eventdetails
Objectdevice
HIDDeviceorigin
string (可选) - 设备已被撤销的来源。
在调用 HIDDevice.forget()
后发出。 当使用 setDevicePermissionHandler
时,此事件可用于帮助维护权限的持久存储。
事件:'select-serial-port'
返回
event
EventportList
SerialPort[]webContents
WebContentscallback
FunctionportId
string
当调用 navigator.serial.requestPort
时需要选择串行端口时发出。 callback
应该使用要选择的 portId
调用,传递空字符串给 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'
返回
event
Eventport
SerialPortwebContents
WebContents
在调用 navigator.serial.requestPort
并且 select-serial-port
已触发后,如果在调用 select-serial-port
的回调之前有新的串行端口可用,则发出此事件。 此事件旨在用于使用 UI 要求用户选择端口,以便 UI 可以使用新添加的端口进行更新。
事件:'serial-port-removed'
返回
event
Eventport
SerialPortwebContents
WebContents
在调用 navigator.serial.requestPort
并且 select-serial-port
已触发后,如果在调用 select-serial-port
的回调之前串行端口已被移除,则发出此事件。 此事件旨在用于使用 UI 要求用户选择端口,以便 UI 可以更新以移除指定端口。
事件:'serial-port-revoked'
返回
event
Eventdetails
Objectport
SerialPortframe
WebFrameMain | null - 触发此事件的帧。 如果在帧导航或销毁后访问,则可能为null
。origin
string - 设备已被撤销的来源。
在调用 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
Eventdetails
ObjectdeviceList
USBDevice[]frame
WebFrameMain | null - 触发此事件的帧。 如果在帧导航或销毁后访问,则可能为null
。
callback
FunctiondeviceId
string (可选)
当调用 navigator.usb.requestDevice
时需要选择 USB 设备时发出。 callback
应使用要选择的 deviceId
进行调用;不向 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'
返回
event
Eventdevice
USBDevicewebContents
WebContents
在调用 navigator.usb.requestDevice
并且 select-usb-device
已触发后,如果在调用 select-usb-device
的回调之前有新设备可用,则发出此事件。 此事件旨在用于使用 UI 要求用户选择设备,以便 UI 可以使用新添加的设备进行更新。
事件:'usb-device-removed'
返回
event
Eventdevice
USBDevicewebContents
WebContents
在调用 navigator.usb.requestDevice
并且 select-usb-device
已触发后,如果在调用 select-usb-device
的回调之前设备已被移除,则发出此事件。 此事件旨在用于使用 UI 要求用户选择设备,以便 UI 可以更新以移除指定设备。
事件:'usb-device-revoked'
返回
event
Eventdetails
Objectdevice
USBDeviceorigin
string (可选) - 设备已被撤销的来源。
在调用 USBDevice.forget()
后发出。 当使用 setDevicePermissionHandler
时,此事件可用于帮助维护权限的持久存储。
实例方法
以下方法在 Session
实例上可用
ses.getCacheSize()
返回 Promise<Integer>
- 会话当前缓存大小,单位为字节。
ses.clearCache()
返回 Promise<void>
- 在缓存清除操作完成后解决。
清除会话的 HTTP 缓存。
ses.clearStorageData([options])
返回 Promise<void>
- 在存储数据清除完成后解决。
ses.flushStorageData()
将任何未写入的 DOMStorage 数据写入磁盘。
ses.setProxy(config)
config
ProxyConfig
返回 Promise<void>
- 在代理设置过程完成后解决。
设置代理设置。
您可能需要 ses.closeAllConnections
来关闭当前正在进行的连接,以防止池化套接字使用先前的代理被未来的请求重用。
ses.resolveHost(host, [options])
host
string - 要解析的主机名。
返回 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)
使用给定配置为 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)
预连接给定数量的套接字到源。
ses.closeAllConnections()
返回 Promise<void>
- 在所有连接关闭时解决。
这将终止/失败所有当前正在进行的请求。
ses.fetch(input[, init])
input
string | GlobalRequestinit
RequestInit & { bypassCustomProtocolHandlers?: boolean } (可选)
返回 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
Function | nullrequest
Objecthostname
stringcertificate
CertificatevalidatedCertificate
CertificateisIssuedByKnownRoot
boolean - 如果 Chromium 识别根 CA 为标准根,则为true
。 如果不是,则可能是此证书是由 MITM 代理生成的,其根已在本地安装(例如,由公司代理)。 如果verificationResult
不是OK
,则不应信任此证书。verificationResult
string - 如果证书受信任,则为OK
,否则为错误,如CERT_REVOKED
。errorCode
Integer - 错误代码。
callback
FunctionverificationResult
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
Function | nullwebContents
WebContents - 请求权限的 WebContents。 请注意,如果请求来自子帧,您应该使用requestingUrl
检查请求源。permission
string - 请求的权限类型。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
- 请求创建通知并通过 Notifications API 在用户系统托盘中显示它们的能力。pointerLock
- 请求通过 指针锁定 API 将鼠标移动直接解释为输入方法。 这些请求始终看起来源自主帧。keyboardLock
- 请求通过 键盘锁定 API 捕获物理键盘上任意或所有按键的按键事件。 这些请求始终看起来源自主帧。openExternal
- 请求在外部应用程序中打开链接。speaker-selection
- 请求通过 speaker-selection 权限策略 枚举和选择音频输出设备。storage-access
- 允许在第三方上下文中加载的内容使用 存储访问 API 请求访问第三方 Cookie。top-level-storage-access
- 允许顶级站点使用 存储访问 API 代表来自同一相关网站集中另一个站点的嵌入内容请求第三方 Cookie 访问。window-management
- 请求使用getScreenDetails
API 枚举屏幕的访问权限。unknown
- 无法识别的权限请求。fileSystem
- 请求使用 文件系统 API 读、写和文件管理功能。
callback
FunctionpermissionGranted
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> | nullwebContents
(WebContents | null) - 检查权限的 WebContents。 请注意,如果请求来自子帧,您应该使用requestingUrl
检查请求源。 所有进行权限检查的跨源子帧都会将null
webContents 传递给此处理程序,而某些其他权限检查(例如notifications
检查)将始终传递null
。 您应该使用embeddingOrigin
和requestingOrigin
分别确定拥有帧和请求帧的来源。permission
string - 权限检查类型。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
- 使用 Notifications API 配置并向用户显示桌面通知。openExternal
- 在外部应用程序中打开链接。pointerLock
- 通过 指针锁定 API 直接将鼠标移动解释为输入方法。 这些请求始终看起来源自主帧。serial
- 使用 Web Serial API 从串行设备读取和写入。storage-access
- 允许在第三方上下文中加载的内容使用 存储访问 API 请求访问第三方 Cookie。top-level-storage-access
- 允许顶级站点使用 存储访问 API 代表来自同一相关网站集中另一个站点的嵌入内容请求第三方 Cookie 访问。usb
- 使用 WebUSB API 向 Web 公开非标准通用串行总线 (USB) 兼容设备服务。deprecated-sync-clipboard-read
已弃用 - 请求运行document.execCommand("paste")
的访问权限。
requestingOrigin
string - 权限检查的源 URLdetails
Object - 某些属性仅在特定权限类型上可用。embeddingOrigin
string (可选) - 嵌入进行权限检查的帧的帧的源。 仅为进行权限检查的跨源子帧设置。securityOrigin
string (可选) -media
检查的安全源。mediaType
string (可选) - 请求的媒体访问类型,可以是video
、audio
或unknown
。requestingUrl
string (可选) - 请求帧加载的最后一个 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
Function | nullrequest
Objectframe
WebFrameMain | null - 请求媒体访问的帧。 如果在帧导航或销毁后访问,则可能为null
。securityOrigin
String - 发出请求页面的来源。videoRequested
Boolean - 如果网页内容请求了视频流,则为 true。audioRequested
Boolean - 如果网页内容请求了音频流,则为 true。userGesture
Boolean - 当此请求被触发时,用户手势是否活跃。
callback
Functionstreams
Objectvideo
Object | WebFrameMain (可选)id
String - 被授予的流的 ID。 这通常来自 DesktopCapturerSource 对象。name
String - 被授予的流的名称。 这通常来自 DesktopCapturerSource 对象。
audio
String | WebFrameMain (可选) - 如果指定为字符串,可以是loopback
或loopbackWithMute
。 指定回环设备将捕获系统音频,目前仅在 Windows 上受支持。 如果指定了 WebFrameMain,将从该帧捕获音频。enableLocalEcho
Boolean (可选) - 如果audio
是一个 WebFrameMain 并且此项设置为true
,则音频的本地播放不会被静音(例如,使用MediaRecorder
录制设置了此标志的WebFrameMain
将允许音频在录制时通过扬声器播放)。 默认为false
。
opts
Object (可选) macOS 实验性useSystemPicker
Boolean - 如果应使用可用的原生系统选择器,则为 true。 默认为false
。 macOS 实验性
当网页内容通过 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> | nulldetails
ObjectdeviceType
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
从该存储中读取。
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[]> | nulldetails
ObjectprotectedClasses
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
Function | nulldetails
ObjectdeviceId
stringpairingKind
string - 请求的配对提示类型。 以下值之一:confirm
此提示请求确认应配对蓝牙设备。confirmPin
此提示请求确认提供的 PIN 与设备上显示的 PIN 匹配。providePin
此提示请求提供设备的 PIN。
frame
WebFrameMain | null - 触发此处理程序的帧。 如果在帧导航或销毁后访问,则可能为null
。pin
string (可选) - 如果pairingKind
是confirmPin
,则为要验证的 PIN 值。
callback
Functionresponse
Objectconfirmed
boolean - 如果对话框被取消,应传入false
。 如果pairingKind
是confirm
或confirmPin
,此值应指示配对是否已确认。 如果pairingKind
是providePin
,则当提供了值时,该值应为true
。pin
string | null (可选) - 当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 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
stringacceptLanguages
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
ObjectminVersion
string (可选) - 可以是tls1
、tls1.1
、tls1.2
或tls1.3
。 连接到远程服务器时允许的最低 SSL 版本。 默认为tls1
。maxVersion
string (可选) - 可以是tls1.2
或tls1.3
。 连接到远程服务器时允许的最大 SSL 版本。 默认为tls1.3
。disabledCipherSuites
Integer[] (可选) - 应该明确禁止使用的密码套件列表,除了那些被网络内置策略禁用的。 支持的字面形式:0xAABB,其中 AA 是cipher_suite[0]
,BB 是cipher_suite[1]
,定义在 RFC 2246, Section 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
启动 url
处资源的下载。 此 API 将生成一个 DownloadItem,可以通过 will-download 事件访问。
与 webContents.downloadURL
不同,此方法不执行与页面来源相关的任何安全检查。
ses.createInterruptedDownload(options)
允许从上一个 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)
script
PreloadScriptRegistration - 预加载脚本
注册预加载脚本,该脚本将在其关联的上下文类型中在此会话中执行。 对于 frame
上下文,这将在任何 WebContents 的网页首选项中定义的预加载之前运行。
返回 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)
返回 Promise<void>
- 在代码缓存清除操作完成后解决。
ses.getSharedDictionaryUsageInfo()
返回 Promise<SharedDictionaryUsageInfo[]>
- Chromium 网络服务存储中的共享字典信息条目数组。
共享字典用于增强通过网络发送的数据的压缩,特别是使用 Brotli 和 ZStandard。 您无需在 Electron 中调用任何共享字典 API 即可使用此高级 Web 功能,但如果您调用,它们允许更深入地控制和检查解压缩期间使用的共享字典。
要获取特定共享字典条目的详细信息,请调用 getSharedDictionaryInfo(options)
。
ses.getSharedDictionaryInfo(options)
返回 Promise<SharedDictionaryInfo[]>
- Chromium 网络服务存储中的共享字典信息条目数组。
要获取所有现有共享字典的信息,请调用 getSharedDictionaryUsageInfo()
。
ses.clearSharedDictionaryCache()
返回 Promise<void>
- 在内存和磁盘中的字典缓存清除后解决。
ses.clearSharedDictionaryCacheForIsolationKey(options)
返回 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 扩展的目录的路径
返回 Promise<Extension>
- 在扩展加载时解决。
如果扩展无法加载,此方法将引发异常。 如果安装扩展时有警告(例如,如果扩展请求 Electron 不支持的 API),则它们将记录到控制台。
请注意,Electron 不支持所有 Chrome 扩展 API。 有关支持的详细信息,请参阅 Supported Extensions APIs。
请注意,在 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.extensions.loadExtension
API。
ses.removeExtension(extensionId)
已弃用
extensionId
string - 要删除的扩展 ID
卸载扩展。
此 API 不能在 app
模块的 ready
事件发出之前调用。
已弃用: 请使用新的 ses.extensions.removeExtension
API。
ses.getExtension(extensionId)
已弃用
extensionId
string - 要查询的扩展 ID
返回 Extension | null
- 具有给定 ID 的已加载扩展。
此 API 不能在 app
模块的 ready
事件发出之前调用。
已弃用: 请使用新的 ses.extensions.getExtension
API。
ses.getAllExtensions()
已弃用
返回 Extension[]
- 所有已加载扩展的列表。
此 API 不能在 app
模块的 ready
事件发出之前调用。
已弃用: 请使用新的 ses.extensions.getAllExtensions
API。
ses.getStoragePath()
返回 string | null
- 此会话数据在磁盘上持久化的绝对文件系统路径。 对于内存会话,此项返回 null
。
ses.clearData([options])
返回 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.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)
})