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
string 获取的 session 实例。 如果存在具有相同 partition
的现有 Session
,则返回该实例;否则将使用 options
创建新的 Session
实例。
如果 partition
以 persist:
开头,页面将使用对应用中所有具有相同 partition
的页面都可用的持久化 session。 如果没有 persist:
前缀,页面将使用内存中的 session。 如果 partition
为空,则返回应用的默认 session。
要使用 options
创建 Session
,您必须确保具有该 partition
的 Session
之前从未使用过。 无法更改现有 Session
对象的 options
。
session.fromPath(path[, options])
path
string
返回 Session
- 从 path
string 指定的绝对路径获取的 session 实例。 如果存在具有相同绝对路径的现有 Session
,则返回该实例;否则将使用 options
创建新的 Session
实例。 如果路径不是绝对路径,则调用将抛出错误。 此外,如果提供了空字符串,也将抛出错误。
要使用 options
创建 Session
,您必须确保具有该 path
的 Session
之前从未使用过。 无法更改现有 Session
对象的 options
。
属性
session
模块具有以下属性
session.defaultSession
一个 Session
对象,即应用的默认 session 对象。
类: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()
将取消下载,并且从进程的下一个 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'
返回
event
Eventextension
Extension
扩展加载后触发。 每当扩展被添加到“已启用”扩展集合时,就会发生此事件。 这包括
- 从
Session.loadExtension
加载的扩展。 - 正在重新加载的扩展
- 从崩溃中恢复。
- 如果扩展请求重新加载 (
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 - 如果渲染器请求连接包含凭据,则为 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 字典文件下载失败时触发。 有关失败的详细信息,您应该收集 netlog 并检查下载请求。
事件:'select-hid-device'
返回
event
Eventdetails
ObjectdeviceList
HIDDevice[]frame
WebFrameMain | null - 触发此事件的帧。 如果在帧已导航或被销毁后访问,则可能为null
。
callback
FunctiondeviceId
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
Eventdetails
Objectdevice
HIDDeviceframe
WebFrameMain | null - 触发此事件的帧。 如果在帧已导航或被销毁后访问,则可能为null
。
在调用 navigator.hid.requestDevice
并且在调用 select-hid-device
的回调之前有新设备可用时触发。 此事件旨在用于使用 UI 要求用户选择设备,以便 UI 可以更新新添加的设备。
事件:'hid-device-removed'
返回
event
Eventdetails
Objectdevice
HIDDeviceframe
WebFrameMain | null - 触发此事件的帧。 如果在帧已导航或被销毁后访问,则可能为null
。
在调用 navigator.hid.requestDevice
并且在调用 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
时需要选择串口时触发。 应使用要选择的 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'
返回
event
Eventport
SerialPortwebContents
WebContents
在调用 navigator.serial.requestPort
并且在调用 select-serial-port
的回调之前有新串口可用时触发。 此事件旨在用于使用 UI 要求用户选择端口,以便 UI 可以更新新添加的端口。
事件:'serial-port-removed'
返回
event
Eventport
SerialPortwebContents
WebContents
在调用 navigator.serial.requestPort
并且在调用 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 设备时触发。 应使用要选择的 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'
返回
event
Eventdevice
USBDevicewebContents
WebContents
在调用 navigator.usb.requestDevice
并且在调用 select-usb-device
的回调之前有新设备可用时触发。 此事件旨在用于使用 UI 要求用户选择设备,以便 UI 可以更新新添加的设备。
事件:'usb-device-removed'
返回
event
Eventdevice
USBDevicewebContents
WebContents
在调用 navigator.usb.requestDevice
并且在调用 select-usb-device
的回调之前设备已被移除时触发。 此事件旨在用于使用 UI 要求用户选择设备,以便 UI 可以更新以移除指定的设备。
事件:'usb-device-revoked'
返回
event
Eventdetails
Objectdevice
USBDeviceorigin
string (可选) - 设备已被撤销权限的源。
调用 USBDevice.forget()
后触发。 当使用 setDevicePermissionHandler
时,此事件可用于帮助维护权限的持久存储。
实例方法
以下方法在 Session
的实例上可用
ses.getCacheSize()
返回 Promise<Integer>
- session 当前的缓存大小,以字节为单位。
ses.clearCache()
返回 Promise<void>
- 缓存清除操作完成时解析。
清除 session 的 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
,将再次从 pacScript
获取 pac 脚本。
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。
使用 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()
,这是一个便利方法,用于从默认 session 发出请求。
有关更多详细信息,请参阅 MDN fetch()
文档。
限制
net.fetch()
不支持data:
或blob:
scheme。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
,每当请求服务器证书验证时,都会使用 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
- 请求创建通知并能够使用 通知 API 在用户系统托盘中显示它们。pointerLock
- 请求通过 Pointer Lock API 直接将鼠标移动解释为输入方法。 这些请求始终看似源自主框架。keyboardLock
- 请求通过 Keyboard Lock 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
函数<布尔值> | nullwebContents
(WebContents | null) - 检查权限的 WebContents。请注意,如果请求来自子帧,则应使用requestingUrl
检查请求来源。所有进行跨源权限检查的子帧都会向此处理程序传递null
webContents,而某些其他权限检查(如notifications
检查)则总是传递null
。您应该使用embeddingOrigin
和requestingOrigin
来分别确定拥有帧和请求帧的来源。permission
字符串 - 权限检查的类型。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
- 允许在第三方上下文中加载的内容使用 存储访问 API 请求访问第三方 Cookie。top-level-storage-access
- 允许顶级网站使用 存储访问 API 代表来自同一相关网站集中的另一个网站的嵌入内容请求第三方 Cookie 访问。usb
- 通过 WebUSB API 向 Web 公开非标准通用串行总线 (USB) 兼容设备服务。deprecated-sync-clipboard-read
已弃用 - 请求运行document.execCommand("paste")
的访问权限
requestingOrigin
字符串 - 权限检查的来源 URLdetails
对象 - 某些属性仅适用于特定权限类型。embeddingOrigin
字符串 (可选) - 嵌入进行权限检查的帧的帧的来源。仅对进行跨源权限检查的子帧设置。securityOrigin
字符串 (可选) -media
检查的安全来源。mediaType
字符串 (可选) - 请求的媒体访问类型,可以是video
、audio
或unknown
requestingUrl
字符串 (可选) - 请求帧加载的最后一个 URL。对于进行跨源权限检查的子帧不提供此参数。isMainFrame
布尔值 - 发出请求的帧是否是主帧
设置可用于响应 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
字符串 - 发出请求的页面的来源。videoRequested
布尔值 - 如果网页内容请求了视频流,则为 true。audioRequested
布尔值 - 如果网页内容请求了音频流,则为 true。userGesture
布尔值 - 触发此请求时,用户手势是否处于活动状态。
callback
Functionstreams
对象video
对象 | WebFrameMain (可选)id
字符串 - 被授予的流的 ID。这通常来自 DesktopCapturerSource 对象。name
字符串 - 被授予的流的名称。这通常来自 DesktopCapturerSource 对象。
audio
字符串 | WebFrameMain (可选) - 如果指定字符串,可以是loopback
或loopbackWithMute
。指定 loopback 设备将捕获系统音频,目前仅在 Windows 上支持。如果指定 WebFrameMain,将捕获该帧的音频。enableLocalEcho
布尔值 (可选) - 如果audio
是一个 WebFrameMain 且此参数设为true
,则音频的本地播放将不会被静音 (例如,使用MediaRecorder
录制设置此标志为true
的 WebFrameMain 将允许音频在录制时通过扬声器播放)。默认值为false
。
opts
对象 (可选) macOS 实验性useSystemPicker
布尔值 - 如果应使用可用的原生系统选择器,则为 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
函数<布尔值> | nulldetails
ObjectdeviceType
字符串 - 正在请求权限的设备类型,可以是hid
、serial
或usb
。origin
字符串 - 设备权限检查的来源 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
函数<字符串[]> | nulldetails
ObjectprotectedClasses
字符串[] - 受保护 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
字符串pairingKind
字符串 - 请求的配对提示类型。以下值之一confirm
此提示请求确认是否应配对蓝牙设备。confirmPin
此提示请求确认提供的 PIN 是否与设备上显示的 PIN 匹配。providePin
此提示请求为设备提供一个 PIN。
frame
WebFrameMain | null - 触发此处理程序的帧。如果在帧已导航或销毁后访问,可能为null
。pin
字符串 (可选) - 如果pairingKind
是confirmPin
,则用于验证的 PIN 值。
callback
Functionresponse
对象confirmed
布尔值 - 如果对话框被取消,应传入false
。如果pairingKind
是confirm
或confirmPin
,此值应表示配对是否已确认。如果pairingKind
是providePin
,提供值时此值应为true
。pin
字符串 | 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
字符串 - 启用集成认证的服务器的逗号分隔列表。
动态设置是否总是为 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
字符串acceptLanguages
字符串 (可选)
覆盖此会话的 userAgent
和 acceptLanguages
。
acceptLanguages
必须是逗号分隔的有序语言代码列表,例如 "en-US,fr,de,ko,zh-CN,ja"
。
这不会影响现有的 WebContents
,每个 WebContents
可以使用 webContents.setUserAgent
来覆盖会话范围的用户代理。
ses.isPersistent()
返回 布尔值
- 此会话是否是持久性会话。BrowserWindow
的默认 webContents
会话是持久性的。从分区创建会话时,以 persist:
开头的会话将是持久性的,而其他会话将是临时的。
ses.getUserAgent()
返回 字符串
- 此会话的用户代理。
ses.setSSLConfig(config)
config
对象minVersion
字符串 (可选) - 可以是tls1
、tls1.1
、tls1.2
或tls1.3
。连接远程服务器时允许的最小 SSL 版本。默认值为tls1
。maxVersion
字符串 (可选) - 可以是tls1.2
或tls1.3
。连接远程服务器时允许的最大 SSL 版本。默认值为tls1.3
。disabledCipherSuites
整数[] (可选) - 应明确阻止使用的密码套件列表,这些套件是除了网络内置策略禁用之外的。支持的字面形式: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
字符串 - 有效的 UUID。
返回 Promise<Buffer>
- 解析为 Blob 数据。
ses.downloadURL(url[, options])
url
字符串
发起对 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
字符串[] - 预加载脚本的绝对路径数组
添加将在此会话关联的所有网页内容上执行的脚本,这些脚本在正常 preload
脚本运行之前执行。
已弃用:请使用新的 ses.registerPreloadScript
API。
ses.getPreloads()
已弃用
返回 字符串[]
- 已注册的预加载脚本路径数组。
已弃用:请使用新的 ses.getPreloadScripts
API。此方法仅返回 frame
上下文类型的预加载脚本路径。
ses.registerPreloadScript(script)
script
PreloadScriptRegistration - 预加载脚本
注册预加载脚本,该脚本将在其在此会话中关联的上下文类型中执行。对于 frame
上下文,这将在 WebContents 的 web preferences 中定义的任何预加载脚本之前运行。
返回 字符串
- 已注册预加载脚本的 ID。
ses.unregisterPreloadScript(id)
id
字符串 - 预加载脚本 ID
取消注册脚本。
ses.getPreloadScripts()
返回 PreloadScript[]:已注册的预加载脚本路径数组。
ses.setCodeCachePath(path)
path
字符串 - 存储来自渲染器的 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
布尔值
设置是否启用内置拼写检查器。
ses.isSpellCheckerEnabled()
返回 布尔值
- 是否启用内置拼写检查器。
ses.setSpellCheckerLanguages(languages)
languages
字符串[] - 要启用拼写检查器的语言代码数组。
内置拼写检查器不会自动检测用户正在输入的语言。为了让拼写检查器正确检查单词,您必须使用语言代码数组调用此 API。您可以使用 ses.availableSpellCheckerLanguages
属性获取支持的语言代码列表。
注意:在 macOS 上,使用的是 OS 拼写检查器,它会自动检测您的语言。此 API 在 macOS 上无效。
ses.getSpellCheckerLanguages()
返回 字符串[]
- 已启用拼写检查器的语言代码数组。如果此列表为空,拼写检查器将回退到使用 en-US
。默认情况下,在启动时,如果此设置为空列表,Electron 将尝试使用当前 OS 区域设置填充此设置。此设置在重启后仍然保留。
注意:在 macOS 上,使用的是 OS 拼写检查器,它有自己的语言列表。在 macOS 上,此 API 将返回 OS 配置的任何语言。
ses.setSpellCheckerDictionaryDownloadURL(url)
url
字符串 - 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 上,使用的是 OS 拼写检查器,因此我们不会下载任何字典文件。此 API 在 macOS 上无效。
ses.listWordsInSpellCheckerDictionary()
返回 Promise<字符串[]>
- 应用自定义词典中所有单词的数组。在从磁盘加载完整词典时解析。
ses.addWordToSpellCheckerDictionary(word)
word
字符串 - 您要添加到词典中的单词
返回 布尔值
- 单词是否成功写入自定义词典。此 API 不适用于非持久性(内存中)会话。
注意:在 macOS 和 Windows 10 上,此单词也将写入 OS 自定义词典。
ses.removeWordFromSpellCheckerDictionary(word)
word
字符串 - 您要从词典中移除的单词
返回 布尔值
- 单词是否成功从自定义词典中移除。此 API 不适用于非持久性(内存中)会话。
注意:在 macOS 和 Windows 10 上,此单词也将从 OS 自定义词典中移除。
ses.loadExtension(path[, options])
已弃用
path
字符串 - 包含未打包 Chrome 扩展的目录路径
返回 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.extensions.loadExtension
API。
ses.removeExtension(extensionId)
已弃用
extensionId
字符串 - 要移除的扩展 ID
卸载扩展。
注意:此 API 不能在 app
模块的 ready
事件触发之前调用。
已弃用:请使用新的 ses.extensions.removeExtension
API。
ses.getExtension(extensionId)
已弃用
extensionId
字符串 - 要查询的扩展 ID
返回 Extension | null
- 给定 ID 的已加载扩展。
注意:此 API 不能在 app
模块的 ready
事件触发之前调用。
已弃用:请使用新的 ses.extensions.getExtension
API。
ses.getAllExtensions()
已弃用
返回 Extension[]
- 所有已加载扩展的列表。
注意:此 API 不能在 app
模块的 ready
事件触发之前调用。
已弃用:请使用新的 ses.extensions.getAllExtensions
API。
ses.getStoragePath()
返回 字符串 | 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)
})