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
Returns Session
- 根据partition
字符串产生的session实例。 当这里已存在一个Session
具有相同的partition
, 它将被返回; 否则一个新的Session
实例将根据options
被创建。
如果 partition
以 persist:
开头, 该页面将使用持续的 session,并在所有页面生效,且使用同一个partition
. 如果没有 persist:
前缀, 页面将使用 in-memory session. 如果没有设置partition
,app 将返回默认的session。
要根据options
创建Session
,你需要确保Session
的partition
在之前从未被使用。 没有办法修改一个已存在的Session
对象的options
。
session.fromPath(path[, options])
path
string
Returns Session
- A session instance from the absolute path as specified by the path
string. When there is an existing Session
with the same absolute path, it will be returned; otherwise a new Session
instance will be created with options
. The call will throw an error if the path is not an absolute path. Additionally, an error will be thrown if an empty string is provided.
To create a Session
with options
, you have to ensure the Session
with the path
has never been used before. 没有办法修改一个已存在的Session
对象的options
。
属性
session
模块具有以下方法:
session.defaultSession
一个Session
对象,该应用程序的默认session对象。
类: Session
获取和设置Session的属性。
Process: Main
此类不从 'electron'
模块导出. 它只能作为 Electron API 中其他方法的返回值。
你可以创建一个 Session
对象在session
模块中。
const { session } = require('electron')
const ses = session.fromPartition('persist:name')
console.log(ses.getUserAgent())
实例事件
以下事件会在Session
实例触发。
Event: 'will-download'
返回:
event
Eventitem
DownloadItemwebContents
WebContents
当 Electron 刚要在webContents
中下载item
的时候触发。
调用event.preventDefault()
方法,将会停止下载,并且在进程的next 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)
})
})
Event: 'extension-loaded'
返回:
event
Eventextension
Extension
在扩展插件加载完成后触发。 当一个扩展插件被添加到 "enabled" 的扩展插件集合内部时, 将自动触发 这包括:
- 扩展插件正在从
Session.loadExtension
中被加载 - 扩展插件正在被重新加载:
- 由于崩溃
- 扩展插件被请求重新载入 (
chrome.runtime.reload()
).
Event: 'extension-unloaded'
返回:
event
Eventextension
Extension
当一个扩展插件被卸载后触发。 当 Session.removeExtension
被调用时也会触发。
Event: 'extension-ready'
返回:
event
Eventextension
Extension
当一个扩展插件加载完成,同时所有必要的浏览器状态也初始化完毕,允许启动插件背景页面时, 将触发此事件。
Event: 'file-system-access-restricted'
返回:
event
Eventdetails
Objectorigin
string - The origin that initiated access to the blocked path.isDirectory
boolean - Whether or not the path is a directory.path
string - The blocked path attempting to be accessed.
callback
Functionaction
string - The action to take as a result of the restricted path access attempt.allow
- This will allowpath
to be accessed despite restricted status.deny
- This will block the access request and trigger anAbortError
.tryAgain
- This will open a new file picker and allow the user to choose another path.
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()
})
Event: 'preconnect'
返回:
event
EventpreconnectUrl
string - 渲染进程进行预连接时请求的 URLallowCredentials
boolean - 为 true 代表渲染进程要求此连接包含 credentials 信息(详见此 规范)
当渲染进程已经预链接到 URL 后将触发此事件, 通常用于 资源加载 提醒
Event: 'spellcheck-dictionary-initialized'
返回:
event
EventlanguageCode
string - 字典文件的语言代码
当一个hunspell字典初始化成功时触发。 这个事件在文件被下载之后触发。
Event: 'spellcheck-dictionary-download-begin'
返回:
event
EventlanguageCode
string - 字典文件的语言代码
当 hunspell 字典文件开始下载时触发
Event: 'spellcheck-dictionary-download-success'
返回:
event
EventlanguageCode
string - 字典文件的语言代码
当 hunspell 字典文件下载成功触发
Event: 'spellcheck-dictionary-download-failure'
返回:
event
EventlanguageCode
string - 字典文件的语言代码
当hunspell字典下载失败时触发。 如果需要详细信息,你应当查看网络日志并且检查下载请求。
Event: 'select-hid-device'
返回:
event
Eventdetails
ObjectdeviceList
HIDDevice[]frame
WebFrameMain
callback
FunctiondeviceId
string | null (optional)
调用 navigator.hid.requestDevice
并要求选择一个输入设备时,会触发此事件。 需在选中 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)
})
})
Event: 'hid-device-added'
返回:
event
Eventdetails
Objectdevice
HIDDeviceframe
WebFrameMain
如果在 select-hid-device
回调被调用之前有新设备变为可用,会在 navigator.hid.requestDevice
被调用和 select-hid-device
触发后触发。 此事件用于使用 UI 让用户选择设备,以便可以使用新添加的设备更新 UI。
Event: 'hid-device-removed'
返回:
event
Eventdetails
Objectdevice
HIDDeviceframe
WebFrameMain
如果在 select-hid-device
回调被调用之前有设备被移除,会在 navigator.hid.requestDevice
被调用和 select-hid-device
触发后触发。 此事件用于使用 UI 让用户选择设备,以便可以移除指定的设备来更新 UI。
Event: 'hid-device-revoked'
返回:
event
Eventdetails
Objectdevice
HIDDeviceorigin
string (optional) - 已被取消的设备。
当 HIDDevice.forget()
被调用后触发。 该事件被用于当 setDevicePermissionHandler
被使用时帮助维护权限的持久存储。
Event: 'select-serial-port'
返回:
event
EventportList
SerialPort[]webContents
WebContentscallback
FunctionportId
string
调用 navigator.serial.requestPort
并选择一系列端口时触发此事件。 callback
方法将在portId
被选中后调用, 给callback
方法一个空字符串参数将取消请求。 此外, navigator.serial
的许可权可以通过使用 ses.setPermissionCheckHandler(handler) 来设置 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)
}
})
})
Event: 'serial-port-added'
返回:
event
Eventport
SerialPortwebContents
WebContents
如果在 select-serial-port
回调被调用之前有新端口变为可用,会在 navigator.serial.requestPort
被 调用和 select-serial-port
触发后触发。 此事件用于使用 UI 让用户选择端口,以便可以使用新添加的端口更新 UI。
Event: 'serial-port-removed'
返回:
event
Eventport
SerialPortwebContents
WebContents
如果在 select-serial-port
回调被调用之前有端口被移除,会在 navigator.serial.requestPort
被调用和 select-serial-port
触发后触发。 此事件用于使用 UI 让用户选择端口,以便可以移除指定的端口来更新 UI。
Event: 'serial-port-revoked'
返回:
event
Eventdetails
Objectport
SerialPortframe
WebFrameMainorigin
string - The origin that the device has been revoked from.
Emitted after SerialPort.forget()
has been called. This event can be used to help maintain persistent storage of permissions when setDevicePermissionHandler
is used.
// 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()
}
Event: 'select-usb-device'
返回:
event
Eventdetails
ObjectdeviceList
USBDevice[]frame
WebFrameMain
callback
FunctiondeviceId
string (optional)
调用 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)
})
})
Event: 'usb-device-added'
返回:
event
Eventdevice
USBDevicewebContents
WebContents
Emitted after navigator.usb.requestDevice
has been called and select-usb-device
has fired if a new device becomes available before the callback from select-usb-device
is called. 此事件用于使用 UI 让用户选择设备,以便可以使用新添加的设备更新 UI。
Event: 'usb-device-removed'
返回:
event
Eventdevice
USBDevicewebContents
WebContents
Emitted after navigator.usb.requestDevice
has been called and select-usb-device
has fired if a device has been removed before the callback from select-usb-device
is called. 此事件用于使用 UI 让用户选择设备,以便可以移除指定的设备来更新 UI。
Event: 'usb-device-revoked'
返回:
event
Eventdetails
Objectdevice
USBDeviceorigin
string (optional) - 已被取消的设备。
Emitted after USBDevice.forget()
has been called. 该事件被用于当 setDevicePermissionHandler
被使用时帮助维护权限的持久存储。
实例方法
在Session
实例对象中,有以下方法:
ses.getCacheSize()
Returns Promise<Integer>
- 当前 session 会话缓存大小,用 byte 字节作为单位。
ses.clearCache()
Returns Promise<void>
- 当缓存清除操作完成时可获取
清除session的HTTP缓存。
ses.clearStorageData([options])
Returns Promise<void>
- 当存储的数据已经被清理时可获得
ses.flushStorageData()
写入任何未写入DOMStorage数据到磁盘.
ses.setProxy(config)
config
ProxyConfig
返回 Promise<void>
- 代理设置进程完成。
代理设置
您可能需要 ses.closeAllConnections
关闭当前在飞行连接,以防止使用以前代理服务器的集合套接口被未来请求重新使用。
ses.resolveHost(host, [options])
host
string - Hostname to resolve.
Returns Promise<ResolvedHost> - Resolves with the resolved IP addresses for the host
.
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)
选项
对象offline
boolean (optional) - Whether to emulate network outage. Defaults to false.latency
Double (optional) - RTT in ms. Defaults to 0 which will disable latency throttling.downloadThroughput
Double (optional) - Download rate in Bps. Defaults to 0 which will disable download throttling.uploadThroughput
Double (optional) - Upload rate in Bps. Defaults to 0 which will disable upload throttling.
通过指定的配置为 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)
选项
对象url
string - URL for preconnect. Only the origin is relevant for opening the socket.numSockets
number (optional) - number of sockets to preconnect. Must be between 1 and 6. Defaults to 1.
Preconnects the given number of sockets to an origin.
ses.closeAllConnections()
Returns Promise<void>
- Resolves when all connections are closed.
Note: It will terminate / fail all requests currently in flight.
ses.fetch(input[, init])
input
string | GlobalRequestinit
RequestInit & { bypassCustomProtocolHandlers?: boolean } (optional)
Returns Promise<GlobalResponse>
- see Response.
Sends a request, similarly to how fetch()
works in the renderer, using Chrome's network stack. This differs from Node's fetch()
, which uses Node.js's HTTP stack.
示例:
async function example () {
const response = await net.fetch('https://my.app')
if (response.ok) {
const body = await response.json()
// ... use the result.
}
}
See also net.fetch()
, a convenience method which issues requests from the default session.
See the MDN documentation for fetch()
for more details.
局限性:
net.fetch()
does not support thedata:
orblob:
schemes.- The value of the
integrity
option is ignored. - The
.type
and.url
values of the returnedResponse
object are incorrect.
By default, requests made with net.fetch
can be made to custom protocols as well as file:
, and will trigger webRequest handlers if present. When the non-standard bypassCustomProtocolHandlers
option is set in RequestInit, custom protocol handlers will not be called for this request. This allows forwarding an intercepted request to the built-in handler. webRequest handlers will still be triggered when bypassing custom protocols.
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()
Disables any network emulation already active for the session
. Resets to the original network configuration.
ses.setCertificateVerifyProc(proc)
proc
Function | nullrequest
Objecthostname
stringcertificate
CertificatevalidatedCertificate
CertificateisIssuedByKnownRoot
boolean -true
if Chromium recognises the root CA as a standard root. If it isn't then it's probably the case that this certificate was generated by a MITM proxy whose root has been installed locally (for example, by a corporate proxy). This should not be trusted if theverificationResult
is notOK
.verificationResult
string -OK
if the certificate is trusted, otherwise an error likeCERT_REVOKED
.errorCode
Integer - 错误代码
callback
FunctionverificationResult
Integer - Value can be one of certificate error codes from here. Apart from the certificate error codes, the following special codes can be used.-0
- 表示成功并禁用证书透明度验证-2
- 表示失败-3
- 使用chromium的验证结果
每当一个服务器证书请求验证,proc
将被这样 proc(request, callback)
调用,为 session
设置证书验证过程。 回调函数 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)
}
})