session
管理浏览器会话、Cookies、缓存、代理设置等。
进程:主进程
🌐 Process: Main
session 模块可用于创建新的 Session 对象。
🌐 The session module can be used to create new Session objects.
你还可以通过使用 WebContents 的 session 属性,或者从 session 模块,访问现有页面的 session。
🌐 You can also access the session of existing pages by using the session
property of WebContents, or from the session module.
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())
方法
🌐 Methods
session 模块具有以下方法:
🌐 The session module has the following methods:
session.fromPartition(partition[, options])
partition字符串
返回 Session - 来自 partition 字符串的会话实例。如果存在具有相同 partition 的 Session,则返回该实例;否则将使用 options 创建一个新的 Session 实例。
🌐 Returns Session - A session instance from partition string. When there is an existing
Session with the same partition, it will be returned; otherwise a new
Session instance will be created with options.
如果 partition 以 persist: 开头,页面将使用可在应用中所有具有相同 partition 的页面间共享的持久会话。如果没有 persist: 前缀,页面将使用内存会话。如果 partition 为空,则将返回应用的默认会话。
🌐 If partition starts with persist:, the page will use a persistent session
available to all pages in the app with the same partition. if there is no
persist: prefix, the page will use an in-memory session. If the partition is
empty then default session of the app will be returned.
要使用 options 创建一个 Session,你必须确保 partition 的 Session 从未被使用过。无法更改现有 Session 对象的 options。
🌐 To create a Session with options, you have to ensure the Session with the
partition has never been used before. There is no way to change the options
of an existing Session object.
session.fromPath(path[, options])
path字符串
返回 Session - 一个会话实例,来自 path 字符串指定的绝对路径。当存在拥有相同绝对路径的 Session 时,将返回该实例;否则,将使用 options 创建一个新的 Session 实例。如果路径不是绝对路径,调用将抛出错误。此外,如果提供空字符串,也会抛出错误。
🌐 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.
要使用 options 创建一个 Session,你必须确保 path 的 Session 从未被使用过。无法更改现有 Session 对象的 options。
🌐 To create a Session with options, you have to ensure the Session with the
path has never been used before. There is no way to change the options
of an existing Session object.
属性
🌐 Properties
session 模块具有以下属性:
🌐 The session module has the following properties:
session.defaultSession
Session 对象,应用的默认会话对象,在调用 app.whenReady 后可用。
🌐 A Session object, the default session object of the app, available after app.whenReady is called.
类:Session
🌐 Class: Session
获取和设置会话的属性。
进程: 主进程
此类未从 'electron' 模块导出。它仅作为 Electron API 中其他方法的返回值提供。
你可以在 session 模块中创建一个 Session 对象:
🌐 You can create a Session object in the session module:
const { session } = require('electron')
const ses = session.fromPartition('persist:name')
console.log(ses.getUserAgent())
实例事件
🌐 Instance Events
以下事件可在 Session 实例上使用:
🌐 The following events are available on instances of Session:
Event: 'will-download'
返回:
🌐 Returns:
当 Electron 即将在 webContents 中下载 item 时触发。
🌐 Emitted when Electron is about to download item in webContents.
调用 event.preventDefault() 将取消下载,并且 item 从下一个进程周期开始将不可用。
🌐 Calling event.preventDefault() will cancel the download and item will not be
available from next tick of the process.
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'
返回:
🌐 Returns:
event活动extension扩展
在加载扩展后触发。每当将扩展添加到“已启用”扩展集合时,就会发生这种情况。这包括:
🌐 Emitted after an extension is loaded. This occurs whenever an extension is added to the "enabled" set of extensions. This includes:
- 正在从
Session.loadExtension加载扩展。 - 正在重新加载扩展:
- 因车祸。
- 如果扩展请求它(
chrome.runtime.reload())。
Event: 'extension-unloaded'
返回:
🌐 Returns:
event活动extension扩展
在扩展被卸载后触发。当调用 Session.removeExtension 时会发生此情况。
🌐 Emitted after an extension is unloaded. This occurs when
Session.removeExtension is called.
Event: 'extension-ready'
返回:
🌐 Returns:
event活动extension扩展
在扩展加载并且所有必要的浏览器状态初始化完成以支持扩展后台页面启动后触发。
🌐 Emitted after an extension is loaded and all necessary browser state is initialized to support the start of the extension's background page.
Event: 'file-system-access-restricted'
返回:
🌐 Returns:
event活动details对象origin字符串 - 发起访问被阻止路径的来源。isDirectory布尔值 - 路径是否为目录。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()
})
Event: 'preconnect'
返回:
🌐 Returns:
event活动preconnectUrl字符串 - 渲染器正在为其预连接请求的 URL。allowCredentials布尔值 - 如果渲染器请求连接包含凭据,则为 True(更多详细信息请参见 规范)。
当渲染进程请求与某个 URL 进行预连接时触发,通常是由于资源提示引起的。
🌐 Emitted when a render process requests preconnection to a URL, generally due to a resource hint.
Event: 'spellcheck-dictionary-initialized'
返回:
🌐 Returns:
event活动languageCode字符串 - 字典文件的语言代码
当 Hunspell 词典文件成功初始化时会触发此事件。这发生在文件下载完成之后。
🌐 Emitted when a hunspell dictionary file has been successfully initialized. This occurs after the file has been downloaded.
Event: 'spellcheck-dictionary-download-begin'
返回:
🌐 Returns:
event活动languageCode字符串 - 字典文件的语言代码
当 hunspell 字典文件开始下载时发出
🌐 Emitted when a hunspell dictionary file starts downloading
Event: 'spellcheck-dictionary-download-success'
返回:
🌐 Returns:
event活动languageCode字符串 - 字典文件的语言代码
成功下载 hunspell 字典文件时发出
🌐 Emitted when a hunspell dictionary file has been successfully downloaded
Event: 'spellcheck-dictionary-download-failure'
返回:
🌐 Returns:
event活动languageCode字符串 - 字典文件的语言代码
当 Hunspell 字典文件下载失败时触发。有关失败的详细信息,你应收集网络日志并检查下载请求。
🌐 Emitted when a hunspell dictionary file download fails. For details on the failure you should collect a netlog and inspect the download request.
Event: 'select-hid-device'
返回:
🌐 Returns:
event活动details对象deviceListHID设备[]frameWebFrameMain | null - 触发此事件的帧。 如果在帧导航或被销毁后访问,可能为null。
callback函数deviceId字符串 | null(可选)
当在调用 navigator.hid.requestDevice 时需要选择 HID 设备时会触发此事件。应使用 deviceId 调用 callback 以选择设备;如果对 callback 不传递任何参数,将取消该请求。此外,navigator.hid 的权限可以通过使用 ses.setPermissionCheckHandler(handler) 和 ses.setDevicePermissionHandler(handler) 进一步管理。
🌐 Emitted when a HID device needs to be selected when a call to
navigator.hid.requestDevice is made. callback should be called with
deviceId to be selected; passing no arguments to callback will
cancel the request. Additionally, permissioning on navigator.hid can
be further managed by using ses.setPermissionCheckHandler(handler)
and ses.setDevicePermissionHandler(handler).
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'
返回:
🌐 Returns:
event活动details对象deviceHID设备frameWebFrameMain | null - 触发此事件的帧。 如果在帧导航或被销毁后访问,可能为null。
navigator.hid.requestDevice 被调用且 select-hid-device 触发后,如果在 select-hid-device 的回调被调用之前有新设备可用,则会触发此事件。该事件用于在使用用户界面让用户选择设备时更新界面,以显示新添加的设备。
🌐 Emitted after navigator.hid.requestDevice has been called and
select-hid-device has fired if a new device becomes available before
the callback from select-hid-device is called. This event is intended for
use when using a UI to ask users to pick a device so that the UI can be updated
with the newly added device.
Event: 'hid-device-removed'
返回:
🌐 Returns:
event活动details对象deviceHID设备frameWebFrameMain | null - 触发此事件的帧。 如果在帧导航或被销毁后访问,可能为null。
navigator.hid.requestDevice 被调用且 select-hid-device 已触发后,如果在 select-hid-device 回调被调用之前设备被移除,则会发出此事件。此事件旨在用于通过用户界面让用户选择设备,以便更新用户界面以移除指定的设备。
🌐 Emitted after navigator.hid.requestDevice has been called and
select-hid-device has fired if a device has been removed before the callback
from select-hid-device is called. This event is intended for use when using
a UI to ask users to pick a device so that the UI can be updated to remove the
specified device.
Event: 'hid-device-revoked'
返回:
🌐 Returns:
event活动details对象deviceHID设备origin字符串(可选)- 设备被吊销的来源。
HIDDevice.forget() 被调用后触发。可以使用此事件来帮助在使用 setDevicePermissionHandler 时维持权限的持久存储。
🌐 Emitted after HIDDevice.forget() has been called. This event can be used
to help maintain persistent storage of permissions when
setDevicePermissionHandler is used.
Event: 'select-serial-port'
返回:
🌐 Returns:
当在调用 navigator.serial.requestPort 时需要选择串口时会触发此事件。应使用 portId 调用 callback 来进行选择,向 callback 传递空字符串将取消请求。此外,可以通过使用 ses.setPermissionCheckHandler(handler) 并结合 serial 权限来管理 navigator.serial 的权限。
🌐 Emitted when a serial port needs to be selected when a call to
navigator.serial.requestPort is made. callback should be called with
portId to be selected, passing an empty string to callback will
cancel the request. Additionally, permissioning on navigator.serial can
be managed by using ses.setPermissionCheckHandler(handler)
with the serial permission.
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'
返回:
🌐 Returns:
在调用 navigator.serial.requestPort 并且 select-serial-port 触发后,如果在调用 select-serial-port 的回调之前有新的串口可用,则会发出此事件。此事件用于在使用用户界面提示用户选择串口时,以便可以使用新添加的串口更新用户界面。
🌐 Emitted after navigator.serial.requestPort has been called and
select-serial-port has fired if a new serial port becomes available before
the callback from select-serial-port is called. This event is intended for
use when using a UI to ask users to pick a port so that the UI can be updated
with the newly added port.
Event: 'serial-port-removed'
返回:
🌐 Returns:
在调用 navigator.serial.requestPort 并且 select-serial-port 触发后,如果在调用 select-serial-port 的回调之前串口已被移除,则会发出此事件。此事件用于在使用界面(UI)让用户选择端口时,以便界面可以更新以移除指定的端口。
🌐 Emitted after navigator.serial.requestPort has been called and
select-serial-port has fired if a serial port has been removed before the
callback from select-serial-port is called. This event is intended for use
when using a UI to ask users to pick a port so that the UI can be updated
to remove the specified port.
Event: 'serial-port-revoked'
返回:
🌐 Returns:
event活动details对象port串口frameWebFrameMain | null - 触发此事件的帧。 如果在帧导航或被销毁后访问,可能为null。origin字符串 - 设备已被撤销的来源。
在调用 SerialPort.forget() 后触发。可以使用此事件来帮助在使用 setDevicePermissionHandler 时维持权限的持久存储。
🌐 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'
返回:
🌐 Returns:
event活动details对象deviceListUSB设备[]frameWebFrameMain | null - 触发此事件的帧。 如果在帧导航或被销毁后访问,可能为null。
callback函数deviceId字符串(可选)
当调用 navigator.usb.requestDevice 时需要选择 USB 设备时触发。应调用 callback 并使用 deviceId 进行选择;传递空参数给 callback 将取消请求。此外,可以通过使用 ses.setPermissionCheckHandler(handler) 和 ses.setDevicePermissionHandler(handler) 进一步管理 navigator.usb 的权限。
🌐 Emitted when a USB device needs to be selected when a call to
navigator.usb.requestDevice is made. callback should be called with
deviceId to be selected; passing no arguments to callback will
cancel the request. Additionally, permissioning on navigator.usb can
be further managed by using ses.setPermissionCheckHandler(handler)
and ses.setDevicePermissionHandler(handler).
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'
返回:
🌐 Returns:
navigator.usb.requestDevice 被调用且 select-usb-device 触发后,如果在 select-usb-device 回调被调用之前有新设备可用,则会发出此事件。此事件旨在用于通过 UI 提示用户选择设备,以便 UI 可以使用新添加的设备进行更新。
🌐 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. This event is intended for
use when using a UI to ask users to pick a device so that the UI can be updated
with the newly added device.
Event: 'usb-device-removed'
返回:
🌐 Returns:
navigator.usb.requestDevice 被调用后,且如果设备在 select-usb-device 回调被调用之前被移除,则在 select-usb-device 触发后发出此事件。该事件用于在使用用户界面(UI)让用户选择设备时,以便 UI 可以更新以移除指定的设备。
🌐 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. This event is intended for use when using
a UI to ask users to pick a device so that the UI can be updated to remove the
specified device.
Event: 'usb-device-revoked'
返回:
🌐 Returns:
event活动details对象deviceUSB设备origin字符串(可选)- 设备被吊销的来源。
USBDevice.forget() 被调用后触发。可以使用此事件来帮助在使用 setDevicePermissionHandler 时维持权限的持久存储。
🌐 Emitted after USBDevice.forget() has been called. This event can be used
to help maintain persistent storage of permissions when
setDevicePermissionHandler is used.
实例方法
🌐 Instance Methods
Session 实例上可用以下方法:
🌐 The following methods are available on instances of Session:
ses.getCacheSize()
返回 Promise<Integer> —— 会话当前的缓存大小,以字节为单位。
🌐 Returns Promise<Integer> - the session's current cache size, in bytes.
ses.clearCache()
返回 Promise<void> - 当缓存清理操作完成时解析。
🌐 Returns Promise<void> - resolves when the cache clear operation is complete.
清除会话的 HTTP 缓存。
🌐 Clears the session’s HTTP cache.
ses.clearStorageData([options])
返回 Promise<void> - 当存储数据被清除时解决。
🌐 Returns Promise<void> - resolves when the storage data has been cleared.
ses.flushStorageData()
将任何未写入的 DOMStorage 数据写入磁盘。
🌐 Writes any unwritten DOMStorage data to disk.
ses.setProxy(config)
config代理配置
返回 Promise<void> - 当代理设置进程完成时解析。
🌐 Returns Promise<void> - Resolves when the proxy setting process is complete.
设置代理设置。
🌐 Sets the proxy settings.
你可能需要使用 ses.closeAllConnections 来关闭当前正在进行的连接,以防止使用先前代理的连接池套接字被后续请求重用。
🌐 You may need ses.closeAllConnections to close currently in flight connections to prevent
pooled sockets using previous proxy from being reused by future requests.
ses.resolveHost(host, [options])
host字符串 - 要解析的主机名。
返回 Promise<ResolvedHost> - 返回 host 的解析 IP 地址。
🌐 Returns Promise<ResolvedHost> - Resolves with the resolved IP addresses for the host.
ses.resolveProxy(url)
url网址
返回 Promise<string> - 解析 url 的代理信息。
🌐 Returns Promise<string> - Resolves with the proxy information for url.
ses.forceReloadProxyConfig()
返回 Promise<void> - 当代理服务的所有内部状态被重置,并且最新的代理配置(如果已存在)被重新应用时,此操作将完成。如果代理模式为 pac_script,PAC 脚本将从 pacScript 重新获取。
🌐 Returns Promise<void> - Resolves when the all internal states of proxy service is reset and the latest proxy configuration is reapplied if it's already available. The pac script will be fetched from pacScript again if the proxy mode is pac_script.
ses.setDownloadPath(path)
path字符串 - 下载位置。
设置下载保存目录。默认情况下,下载目录将是各自应用文件夹下的 Downloads。
🌐 Sets download saving directory. By default, the download directory will be the
Downloads under the respective app folder.
ses.enableNetworkEmulation(options)
使用给定配置模拟 session 的网络。
🌐 Emulates network with the given configuration for the 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)
将给定数量的套接字预先连接到源。
🌐 Preconnects the given number of sockets to an origin.
ses.closeAllConnections()
返回 Promise<void> - 当所有连接关闭时解析。
🌐 Returns Promise<void> - Resolves when all connections are closed.
它将终止/失败所有当前正在进行的请求。
ses.fetch(input[, init])
input字符串 | 全局请求initRequestInit & { bypassCustomProtocolHandlers?: boolean }(可选)
返回 Promise<GlobalResponse> - 详情请参见 Response。
🌐 Returns Promise<GlobalResponse> - see Response.
发送请求,类似于渲染器中 fetch() 的工作方式,使用的是 Chrome 的网络栈。这与 Node 的 fetch() 不同,后者使用的是 Node.js 的 HTTP 栈。
🌐 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.
示例:
🌐 Example:
async function example () {
const response = await net.fetch('https://my.app')
if (response.ok) {
const body = await response.json()
// ... use the result.
}
}
另请参见 net.fetch(),这是一个便利方法,可从默认会话发出请求。
🌐 See also net.fetch(), a convenience method which
issues requests from the default session.
有关更多详情,请参阅 MDN 文档中的 fetch()。
🌐 See the MDN documentation for
fetch() for more
details.
限制:
🌐 Limitations:
net.fetch()不支持data:或blob:方案。integrity选项的值将被忽略。- 返回的
Response对象的.type和.url值不正确。
默认情况下,使用 net.fetch 发出的请求可以发送到 自定义协议 以及 file:,并且如果存在,会触发 webRequest 处理程序。当在 RequestInit 中设置非标准 bypassCustomProtocolHandlers 选项时,该请求的自定义协议处理程序将不会被调用。这允许将被拦截的请求转发给内置处理程序。绕过自定义协议时,webRequest 处理程序仍然会被触发。
🌐 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()
禁用已为 session 启用的任何网络模拟。恢复到原始网络配置。
🌐 Disables any network emulation already active for the session. Resets to
the original network configuration.
ses.setCertificateVerifyProc(proc)
proc函数 | 空request对象callback函数verificationResult整数 - 值可以是 这里 的证书错误代码之一。除了证书错误代码之外,还可以使用以下特殊代码。0- 表示成功并禁用证书透明度验证。-2- 表示失败。-3- 使用来自 Chromium 的验证结果。
为 session 设置证书验证进程,每当请求服务器证书验证时,将使用 proc 调用 proc(request, callback)。调用 callback(0) 接受证书,调用 callback(-2) 拒绝证书。
🌐 Sets the certificate verify proc for session, the proc will be called with
proc(request, callback) whenever a server certificate
verification is requested. Calling callback(0) accepts the certificate,
calling callback(-2) rejects it.
调用 setCertificateVerifyProc(null) 将恢复为默认的证书验证进程。
🌐 Calling setCertificateVerifyProc(null) will revert back to default certificate
verify proc.
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函数 | 空webContentsWebContents - 请求权限的 WebContents。请注意,如果请求来自子框架,你应该使用requestingUrl来检查请求来源。permission字符串 - 请求权限的类型。clipboard-read- 请求访问以从剪贴板读取。clipboard-sanitized-write- 请求写入剪贴板的权限。display-capture- 请求通过 屏幕捕获 API 访问屏幕捕获权限。fullscreen- 通过 Fullscreen API 请求控制应用的全屏状态。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- 请求通过 扬声器选择权限策略 枚举并选择音频输出设备。storage-access- 允许在第三方环境中加载的内容使用存储访问 API请求访问第三方 Cookie。top-level-storage-access- 允许顶层网站使用 Storage Access API 代表属于同一关联网站集合的另一个网站的嵌入内容请求第三方 Cookie 访问权限。window-management- 请求使用getScreenDetailsAPI 枚举屏幕的访问权限。unknown- 无法识别的权限请求。fileSystem- 请求使用 文件系统 API 的读取、写入和文件管理权限。
callback函数permissionGranted布尔值 - 允许或拒绝该权限。
details权限请求 | 文件系统权限请求 | 媒体访问权限请求 | 打开外部权限请求 - 关于所请求权限的其他信息。
设置可以用于响应 session 权限请求的处理程序。调用 callback(true) 将允许该权限,调用 callback(false) 将拒绝该权限。要清除处理程序,请调用 setPermissionRequestHandler(null)。请注意,你还必须实现 setPermissionCheckHandler 才能完成完整的权限处理。大多数 Web API 会先进行权限检查,如果检查被拒绝,则会发起权限请求。
🌐 Sets the handler which can be used to respond to permission requests for the session.
Calling callback(true) will allow the permission and callback(false) will reject it.
To clear the handler, call setPermissionRequestHandler(null). Please note that
you must also implement setPermissionCheckHandler to get complete permission handling.
Most web APIs do a permission check and then make a permission request if the check is denied.
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)
handlerFunction<boolean> | nulwebContents(WebContents | null) - 检查权限的 WebContents。请注意,如果请求来自子框架,应使用requestingUrl来检查请求来源。所有进行权限检查的跨源子框架都会向此处理程序传递一个null的 webContents,而某些其他权限检查(例如notifications检查)将始终传递null。你应使用embeddingOrigin和requestingOrigin分别确定拥有框架和请求框架的来源。permission字符串 - 权限检查类型。clipboard-read- 请求访问以从剪贴板读取。clipboard-sanitized-write- 请求写入剪贴板的权限。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- 允许顶层网站使用 Storage Access API 代表属于同一关联网站集合的另一个网站的嵌入内容请求第三方 Cookie 访问权限。usb- 使用 WebUSB API 将非标准通用串行总线 (USB) 兼容设备服务暴露到网页。deprecated-sync-clipboard-read已弃用 - 请求访问以运行document.execCommand("paste")fileSystem- 使用 文件系统 API 访问读取、写入和文件管理功能。
requestingOrigin字符串 - 权限检查的原始 URLdetails对象 - 某些属性仅在特定权限类型下可用。embeddingOrigin字符串(可选)- 嵌入进行权限检查的框架的框架来源。仅在跨源子框架进行权限检查时设置。securityOrigin字符串(可选)-media检查的安全来源。mediaType字符串(可选)- 请求的媒体访问类型,可以是video、audio或unknown。requestingUrl字符串(可选)- 请求框架加载的最后一个 URL。对于进行权限检查的跨源子框架,不提供此信息。isMainFrame布尔值 - 发起请求的框架是否为主框架。filePath字符串(可选)-fileSystem请求的路径。isDirectory布尔值(可选)- 指示fileSystem请求是否是一个目录。fileAccessType字符串(可选)-fileSystem请求的访问类型。可以是writable或readable。
设置可用于响应 session 权限检查的处理程序。返回 true 将允许该权限,返回 false 将拒绝该权限。请注意,你还必须实现 setPermissionRequestHandler 才能获得完整的权限处理。大多数 Web API 会先进行权限检查,如果检查被拒绝,则会发起权限请求。要清除处理程序,请调用 setPermissionCheckHandler(null)。
🌐 Sets the handler which can be used to respond to permission checks for the session.
Returning true will allow the permission and false will reject it. Please note that
you must also implement setPermissionRequestHandler to get complete permission handling.
Most web APIs do a permission check and then make a permission request if the check is denied.
To clear the handler, call setPermissionCheckHandler(null).
const { session } = require('electron')
const url = require('node:url')
session.fromPartition('some-partition').setPermissionCheckHandler((webContents, permission, requestingOrigin) => {
if (new URL(requestingOrigin).hostname === 'some-host' && permission === 'notifications') {
return true // granted
}
return false // denied
})
由于 Chromium 的限制,isMainFrame 对于 fileSystem 请求总是会是 false。
ses.setDisplayMediaRequestHandler(handler[, opts])
handler函数 | 空request对象frameWebFrameMain | null - 请求访问媒体的帧。如果在帧导航或被销毁后访问,可能是null。securityOrigin字符串 - 发出请求的页面来源。videoRequested布尔值 - 如果网页内容请求视频流,则为 true。audioRequested布尔值 - 如果网页内容请求了音频流,则为 true。userGesture布尔值 - 当此请求被触发时,用户手势是否处于活动状态。
callback函数streams对象video对象 | WebFrameMain(可选)id字符串 - 被授予的流的 ID。通常,这将来自一个 DesktopCapturerSource 对象。name字符串 - 被授予的流的名称。通常,这将来自一个 DesktopCapturerSource 对象。
audio字符串 | WebFrameMain(可选) - 如果指定的是字符串,可以是loopback或loopbackWithMute。指定回环设备将捕获系统音频,目前仅在 Windows 上受支持。如果指定了 WebFrameMain,则会捕获该框架的音频。enableLocalEcho布尔值(可选)- 如果audio是一个 WebFrameMain,并且此项设置为true,则本地播放的音频不会被静音(例如,使用MediaRecorder录制WebFrameMain并将此标志设置为true时,音频将在录制时传输到扬声器)。默认值为false。
opts对象(可选)macOS 实验性useSystemPicker布尔值 - 如果应使用可用的本地系统选择器,则为 true。默认值为false。macOS 实验性
当网页内容通过 navigator.mediaDevices.getDisplayMedia API 请求访问显示媒体时,将调用此处理程序。使用 desktopCapturer API 来选择授予访问权限的流。
🌐 This handler will be called when web content requests access to display media
via the navigator.mediaDevices.getDisplayMedia API. Use the
desktopCapturer API to choose which stream(s) to grant
access to.
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 对象作为视频或音频流传递,将会从该帧捕获视频或音频流。
🌐 Passing a WebFrameMain object as a video or audio stream will capture the video or audio stream from that frame.
const { session } = require('electron')
session.defaultSession.setDisplayMediaRequestHandler((request, callback) => {
// Allow the tab to capture itself.
callback({ video: request.frame })
})
传递 null 而不是函数会将处理程序重置为默认状态。
🌐 Passing null instead of a function resets the handler to its default state.
ses.setDevicePermissionHandler(handler)
handlerFunction<boolean> | nul
设置用于响应 session 设备权限检查的处理程序。
返回 true 将允许设备,返回 false 将拒绝设备。
要清除处理程序,请调用 setDevicePermissionHandler(null)。
此处理程序可用于在不先请求设备权限的情况下,为设备提供默认权限(例如通过 navigator.hid.requestDevice)。如果未定义此处理程序,则将使用通过设备选择(例如通过 navigator.hid.requestDevice)授予的默认设备权限。
此外,Electron 的默认行为是在内存中存储已授予的设备权限。如果需要长期存储,开发者可以在处理 select-hid-device 事件时存储已授予的设备权限,然后通过 setDevicePermissionHandler 从该存储中读取。
🌐 Sets the handler which can be used to respond to device permission checks for the session.
Returning true will allow the device to be permitted and false will reject it.
To clear the handler, call setDevicePermissionHandler(null).
This handler can be used to provide default permissioning to devices without first calling for permission
to devices (eg via navigator.hid.requestDevice). If this handler is not defined, the default device
permissions as granted through device selection (eg via navigator.hid.requestDevice) will be used.
Additionally, the default behavior of Electron is to store granted device permission in memory.
If longer term storage is needed, a developer can store granted device
permissions (eg when handling the select-hid-device event) and then read from that storage with 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)
handlerFunction<string[]> | nulldetails对象protectedClassesstring[] - 当前受保护的 USB 类列表。可能的类值包括:audioaudio-videohidmass-storagesmart-cardvideowireless
设置可用于覆盖哪些USB 类受到保护的处理程序。处理程序的返回值是一个包含应被视为受保护的 USB 类的字符串数组(例如,在渲染器中不可用)。数组的有效值包括:
🌐 Sets the handler which can be used to override which USB classes are protected. The return value for the handler is a string array of USB classes which should be considered protected (eg not available in the renderer). Valid values for the array are:
audioaudio-videohidmass-storagesmart-cardvideowireless
从处理程序返回一个空字符串数组将允许所有 USB 类;返回传入的数组将保持默认的受保护 USB 类列表(如果未定义处理程序,这也是默认行为)。
要清除处理程序,请调用 setUSBProtectedClassesHandler(null)。
🌐 Returning an empty string array from the handler will allow all USB classes; returning the passed in array will maintain the default list of protected USB classes (this is also the default behavior if a handler is not defined).
To clear the handler, call 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函数 | 空details对象deviceId字符串pairingKind字符串 - 请求的配对提示类型。取以下值之一:confirm此提示正在请求确认是否应配对蓝牙设备。confirmPin此提示正在请求确认所提供的 PIN 是否与设备上显示的 PIN 匹配。providePin该提示请求为该设备提供一个PIN码。
frameWebFrameMain | null - 启动此处理程序的框架。如果在框架导航后或被销毁后访问,可能是null。pin字符串(可选)- 用于验证pairingKind是否为confirmPin的验证码值。
callback函数response对象confirmed布尔值 - 如果对话框被取消,应传入false。如果pairingKind是confirm或confirmPin,此值应指示配对是否已确认。如果pairingKind是providePin,当提供值时,该值应为true。pin字符串 | null(可选)- 当pairingKind为providePin时,此值应为蓝牙设备所需的密码。
设置一个处理程序以响应蓝牙配对请求。该处理程序允许开发者处理在配对前需要额外验证的设备。当未定义处理程序时,在 Linux 或 Windows 上任何需要额外验证的配对将会被自动取消。macOS 不需要处理程序,因为 macOS 会自动处理配对。要清除处理程序,请调用 setBluetoothPairingHandler(null)。
🌐 Sets a handler to respond to Bluetooth pairing requests. This handler
allows developers to handle devices that require additional validation
before pairing. When a handler is not defined, any pairing on Linux or Windows
that requires additional validation will be automatically cancelled.
macOS does not require a handler because macOS handles the pairing
automatically. To clear the handler, call 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 an 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> - 当操作完成时解析。
🌐 Returns Promise<void> - Resolves when the operation is complete.
清除主机解析器缓存。
🌐 Clears the host resolver cache.
ses.allowNTLMCredentialsForDomains(domains)
domains字符串 - 启用了集成身份验证的服务器的逗号分隔列表。
动态设置是否始终为 HTTP NTLM 或协商身份验证发送凭据。
🌐 Dynamically sets whether to always send credentials for HTTP NTLM or Negotiate authentication.
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。
🌐 Overrides the userAgent and acceptLanguages for this session.
acceptLanguages 必须是用逗号分隔的语言代码有序列表,例如 "en-US,fr,de,ko,zh-CN,ja"。
🌐 The acceptLanguages must be a comma separated ordered list of language codes, for
example "en-US,fr,de,ko,zh-CN,ja".
这不会影响现有的 WebContents,每个 WebContents 都可以使用 webContents.setUserAgent 来覆盖会话范围的用户代理。
🌐 This doesn't affect existing WebContents, and each WebContents can use
webContents.setUserAgent to override the session-wide user agent.
ses.isPersistent()
返回 boolean - 指示此会话是否为持久会话。默认 webContents 的 BrowserWindow 会话是持久的。当从分区创建会话时,前缀为 persist: 的会话将是持久的,而其他会话将是临时的。
🌐 Returns boolean - Whether or not this session is a persistent one. The default
webContents session of a BrowserWindow is persistent. When creating a session
from a partition, session prefixed with persist: will be persistent, while others
will be temporary.
ses.getUserAgent()
返回 string - 此会话的用户代理。
🌐 Returns string - The user agent for this session.
ses.setSSLConfig(config)
config对象minVersion字符串(可选)- 可以是tls1、tls1.1、tls1.2或tls1.3。连接远程服务器时允许的最低 SSL 版本。默认值为tls1。maxVersion字符串(可选)- 可以是tls1.2或tls1.3。连接远程服务器时允许的最大 SSL 版本。默认为tls1.3。disabledCipherSuitesInteger[](可选)- 应明确禁止使用的密码套件列表,除了网络内置策略已禁用的套件之外。支持的字面形式: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 连接)不会被终止,但连接池中的旧套接字将不会被用于新的连接。
🌐 Sets the SSL configuration for the session. All subsequent network requests will use the new configuration. Existing network connections (such as WebSocket connections) will not be terminated, but old sockets in the pool will not be reused for new connections.
ses.getBlobData(identifier)
identifier字符串 - 有效的 UUID。
返回 Promise<Buffer> - 解析为二进制数据。
🌐 Returns Promise<Buffer> - resolves with blob data.
ses.downloadURL(url[, options])
url字符串
启动对 url 资源的下载。该 API 将生成一个可以通过 will-download 事件访问的 DownloadItem。
🌐 Initiates a download of the resource at url.
The API will generate a DownloadItem that can be accessed
with the will-download event.
这不会执行与页面来源相关的任何安全检查,
不像 webContents.downloadURL 那样。
ses.createInterruptedDownload(options)
允许从先前的 Session 恢复 cancelled 或 interrupted 下载。API 将生成一个可以通过 will-download 事件访问的 DownloadItem。DownloadItem 不会关联任何 WebContents,初始状态为 interrupted。下载只有在对 DownloadItem 调用 resume API 时才会开始。
🌐 Allows resuming cancelled or interrupted downloads from previous Session.
The API will generate a DownloadItem that can be accessed with the will-download
event. The DownloadItem will not have any WebContents associated with it and
the initial state will be interrupted. The download will start only when the
resume API is called on the DownloadItem.
ses.clearAuthCache()
返回 Promise<void> - 当会话的 HTTP 认证缓存被清除后解析。
🌐 Returns Promise<void> - resolves when the session’s HTTP authentication cache has been cleared.
ses.setPreloads(preloads) 已弃用
🌐 ses.setPreloads(preloads) Deprecated
preloadsstring[] - 预加载脚本的绝对路径数组
在正常 preload 脚本运行之前,添加将在与此会话关联的所有网页内容上执行的脚本。
🌐 Adds scripts that will be executed on ALL web contents that are associated with
this session just before normal preload scripts run.
**已弃用:**请使用新的 ses.registerPreloadScript API。
ses.getPreloads() 已弃用
🌐 ses.getPreloads() Deprecated
返回 string[],这是一个已注册预加载脚本路径的数组。
🌐 Returns string[] an array of paths to preload scripts that have been
registered.
已弃用: 请使用新的 ses.getPreloadScripts API。此方法仅返回 frame 上下文类型的预加载脚本路径。
ses.registerPreloadScript(script)
scriptPreloadScriptRegistration - 预加载脚本
注册预加载脚本,该脚本将在本会话中与其关联的上下文类型中执行。对于 frame 上下文,这将在 WebContents 的网络偏好中定义的任何预加载之前运行。
🌐 Registers preload script that will be executed in its associated context type in this session. For
frame contexts, this will run prior to any preload defined in the web preferences of a
WebContents.
返回 string - 已注册预加载脚本的 ID。
🌐 Returns string - The ID of the registered preload script.
ses.unregisterPreloadScript(id)
id字符串 - 预加载脚本 ID
取消注册脚本。
🌐 Unregisters script.
ses.getPreloadScripts()
返回 PreloadScript[]:一个包含已注册预加载脚本路径的数组。
🌐 Returns PreloadScript[]: An array of paths to preload scripts that have been registered.
ses.setCodeCachePath(path)
path字符串 - 存储渲染器生成的 v8 JS 代码缓存的绝对路径。
设置用于存储本会话生成的 JS 代码缓存 的目录。调用此方法前无需用户手动创建该目录,运行时会在目录不存在时自动创建,否则将使用已存在的目录。如果目录无法创建,则不会使用代码缓存,并且所有与代码缓存相关的操作将在运行时中默默失败。默认情况下,该目录将位于各自用户数据文件夹下的 Code Cache。
🌐 Sets the directory to store the generated JS code cache for this session. The directory is not required to be created by the user before this call, the runtime will create if it does not exist otherwise will use the existing directory. If directory cannot be created, then code cache will not be used and all operations related to code cache will fail silently inside the runtime. By default, the directory will be Code Cache under the
respective user data folder.
请注意,默认情况下代码缓存仅对 http(s) URL 启用,要为自定义协议启用代码缓存,必须在注册协议时指定 codeCache: true 和 standard: true。
🌐 Note that by default code cache is only enabled for http(s) URLs, to enable code
cache for custom protocols, codeCache: true and standard: true must be
specified when registering the protocol.
ses.clearCodeCaches(options)
返回 Promise<void> - 当代码缓存清理操作完成时解析。
🌐 Returns Promise<void> - resolves when the code cache clear operation is complete.
ses.getSharedDictionaryUsageInfo()
返回 Promise<SharedDictionaryUsageInfo[]> —— 一个包含 Chromium 网络服务存储中共享字典信息条目的数组。
🌐 Returns Promise<SharedDictionaryUsageInfo[]> - an array of shared dictionary information entries in Chromium's networking service's storage.
共享字典用于增强通过网络传输的数据压缩,特别是 Brotli 和 ZStandard。你不需要在 Electron 中调用任何共享字典 API 就可以使用这一高级网页功能,但如果你调用,它们可以让你在解压缩进程中对共享字典进行更深入的控制和检查。
🌐 Shared dictionaries are used to power advanced compression of data sent over the wire, specifically with Brotli and ZStandard. You don't need to call any of the shared dictionary APIs in Electron to make use of this advanced web feature, but if you do, they allow deeper control and inspection of the shared dictionaries used during decompression.
要获取有关特定共享字典条目的详细信息,请调用 getSharedDictionaryInfo(options)。
🌐 To get detailed information about a specific shared dictionary entry, call getSharedDictionaryInfo(options).
ses.getSharedDictionaryInfo(options)
返回 Promise<SharedDictionaryInfo[]> —— 一个包含 Chromium 网络服务存储中共享字典信息条目的数组。
🌐 Returns Promise<SharedDictionaryInfo[]> - an array of shared dictionary information entries in Chromium's networking service's storage.
要获取有关所有当前共享字典的信息,请调用 getSharedDictionaryUsageInfo()。
🌐 To get information about all present shared dictionaries, call getSharedDictionaryUsageInfo().
ses.clearSharedDictionaryCache()
返回 Promise<void> - 当字典缓存已被清除(包括内存和磁盘上的缓存)时解决。
🌐 Returns Promise<void> - resolves when the dictionary cache has been cleared, both in memory and on disk.
ses.clearSharedDictionaryCacheForIsolationKey(options)
返回 Promise<void> - 当指定隔离键的字典缓存已被清除(包括内存和磁盘上的缓存)时,解析完成。
🌐 Returns Promise<void> - resolves when the dictionary cache has been cleared for the specified isolation key, both in memory and on disk.
ses.setSpellCheckerEnabled(enable)
enable布尔值
设置是否启用内置拼写检查器。
🌐 Sets whether to enable the builtin spell checker.
ses.isSpellCheckerEnabled()
返回 boolean - 内置拼写检查器是否已启用。
🌐 Returns boolean - Whether the builtin spell checker is enabled.
ses.setSpellCheckerLanguages(languages)
languagesstring[] - 用于启用拼写检查器的语言代码数组。
内置的拼写检查器不会自动检测用户正在输入的语言。为了让拼写检查器正确检查其单词,你必须使用语言代码数组调用此 API。你可以通过 ses.availableSpellCheckerLanguages 属性获取受支持的语言代码列表。
🌐 The built in spellchecker does not automatically detect what language a user is typing in. In order for the
spell checker to correctly check their words you must call this API with an array of language codes. You can
get the list of supported language codes with the ses.availableSpellCheckerLanguages property.
在 macOS 上,系统拼写检查器将被使用,并会自动检测你的语言。该 API 在 macOS 上不起作用。
ses.getSpellCheckerLanguages()
返回 string[] - 拼写检查器启用的语言代码数组。如果此列表为空,拼写检查器将回退使用 en-US。默认情况下,如果启动时此设置为空列表,Electron 会尝试使用当前操作系统的语言环境来填充此设置。此设置在重启后会被保留。
🌐 Returns string[] - An array of language codes the spellchecker is enabled for. If this list is empty the spellchecker
will fallback to using en-US. By default on launch if this setting is an empty list Electron will try to populate this
setting with the current OS locale. This setting is persisted across restarts.
在 macOS 上,使用的是操作系统自带的拼写检查器,并且它有自己的语言列表。在 macOS 上,这个 API 将返回操作系统已配置的所有语言。
ses.setSpellCheckerDictionaryDownloadURL(url)
url字符串 - Electron 用于下载 hunspell 词典的基础 URL。
默认情况下,Electron 会从 Chromium CDN 下载 hunspell 词典。如果你想覆盖此行为,可以使用此 API 将词典下载器指向自己托管的 hunspell 词典版本。我们会随每个版本发布一个 hunspell_dictionaries.zip 文件,其中包含你需要在此处托管的文件。
🌐 By default Electron will download hunspell dictionaries from the Chromium CDN. If you want to override this
behavior you can use this API to point the dictionary downloader at your own hosted version of the hunspell
dictionaries. We publish a hunspell_dictionaries.zip file with each release which contains the files you need
to host here.
文件服务器必须不区分大小写。如果无法做到这一点,你必须上传每个文件两次:一次使用 ZIP 文件中的原始大小写,另一次使用全小写的文件名。
🌐 The file server must be case insensitive. If you cannot do this, you must upload each file twice: once with the case it has in the ZIP file and once with the filename as all lowercase.
如果 hunspell_dictionaries.zip 中的文件可以在 https://example.com/dictionaries/language-code.bdic 获取,那么你应该使用 ses.setSpellCheckerDictionaryDownloadURL('https://example.com/dictionaries/') 调用这个 API。请注意末尾的斜杠。字典的 URL 形成方式为 ${url}${filename}。
🌐 If the files present in hunspell_dictionaries.zip are available at https://example.com/dictionaries/language-code.bdic
then you should call this api with ses.setSpellCheckerDictionaryDownloadURL('https://example.com/dictionaries/'). Please
note the trailing slash. The URL to the dictionaries is formed as ${url}${filename}.
在 macOS 上,使用操作系统自带的拼写检查功能,因此我们不下载任何词典文件。在 macOS 上,此 API 不执行任何操作。
ses.listWordsInSpellCheckerDictionary()
返回 Promise<string[]> - 应用自定义词典中的所有单词数组。
当从磁盘加载完整词典后会被解析。
🌐 Returns Promise<string[]> - An array of all words in app's custom dictionary.
Resolves when the full dictionary is loaded from disk.
ses.addWordToSpellCheckerDictionary(word)
word字符串 - 你想添加到字典中的单词
返回 boolean - 该单词是否成功写入自定义词典。此 API 在非持久(内存)会话中将无法使用。
🌐 Returns boolean - Whether the word was successfully written to the custom dictionary. This API
will not work on non-persistent (in-memory) sessions.
在 macOS 和 Windows 上,这个词也会被写入操作系统的自定义词典。
ses.removeWordFromSpellCheckerDictionary(word)
word字符串 - 你想从字典中删除的单词
返回 boolean - 该单词是否已成功从自定义词典中移除。此 API 在非持久(内存)会话中将无法使用。
🌐 Returns boolean - Whether the word was successfully removed from the custom dictionary. This API
will not work on non-persistent (in-memory) sessions.
在 macOS 和 Windows 上,这个词也将从操作系统的自定义词典中移除。
ses.loadExtension(path[, options]) 已弃用
🌐 ses.loadExtension(path[, options]) Deprecated
path字符串 - 包含已解压 Chrome 扩展程序的目录的路径
返回 Promise<Extension> - 当扩展加载完成时解析。
🌐 Returns Promise<Extension> - resolves when the extension is loaded.
如果扩展无法加载,此方法将引发异常。如果在安装扩展时出现警告(例如,如果扩展请求 Electron 不支持的 API),这些警告将记录到控制台。
🌐 This method will raise an exception if the extension could not be loaded. If there are warnings when installing the extension (e.g. if the extension requests an API that Electron does not support) then they will be logged to the console.
请注意,Electron 不支持 Chrome 扩展 API 的全部功能。有关支持的详细信息,请参阅 Supported Extensions APIs。
🌐 Note that Electron does not support the full range of Chrome extensions APIs. See Supported Extensions APIs for more details on what is supported.
请注意,在以前的 Electron 版本中,加载的扩展会被记住,以便在应用的未来运行中使用。现在情况已经不同:如果你希望扩展在应用启动时被加载,必须在每次启动时调用 loadExtension。
🌐 Note that in previous versions of Electron, extensions that were loaded would
be remembered for future runs of the application. This is no longer the case:
loadExtension must be called on every boot of your app if you want the
extension to be loaded.
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) 扩展名。
🌐 This API does not support loading packed (.crx) extensions.
在 app 模块的 ready 事件被触发之前,无法调用此 API。
将扩展加载到内存(非持久)会话中则不适用 支持,会报错。
**已弃用:**请使用新的 ses.extensions.loadExtension API。
ses.removeExtension(extensionId) 已弃用
🌐 ses.removeExtension(extensionId) Deprecated
extensionId字符串 - 要移除的扩展 ID
卸载扩展。
🌐 Unloads an extension.
在 app 模块的 ready 事件被触发之前,无法调用此 API。
**已弃用:**请使用新的 ses.extensions.removeExtension API。
ses.getExtension(extensionId) 已弃用
🌐 ses.getExtension(extensionId) Deprecated
extensionId字符串 - 要查询的扩展 ID
返回 Extension | null - 具有指定 ID 的已加载扩展。
🌐 Returns Extension | null - The loaded extension with the given ID.
在 app 模块的 ready 事件被触发之前,无法调用此 API。
**已弃用:**请使用新的 ses.extensions.getExtension API。
ses.getAllExtensions() 已弃用
🌐 ses.getAllExtensions() Deprecated
返回 Extension[] - 所有已加载扩展的列表。
🌐 Returns Extension[] - A list of all loaded extensions.
在 app 模块的 ready 事件被触发之前,无法调用此 API。
**已弃用:**请使用新的 ses.extensions.getAllExtensions API。
ses.getStoragePath()
返回 string | null - 数据在磁盘上持久保存的会话的绝对文件系统路径。对于内存中的会话,则返回 null。
🌐 Returns string | null - The absolute file system path where data for this
session is persisted on disk. For in memory sessions this returns null.
ses.clearData([options])
返回 Promise<void> - 当所有数据已清除时解决。
🌐 Returns Promise<void> - resolves when all data has been cleared.
清除各种不同类型的数据。
🌐 Clears various different types of data.
此方法清除的数据类型更多,比 clearStorageData 方法更彻底。
🌐 This method clears more types of data and is more thorough than the
clearStorageData method.
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 接口。
🌐 For more information, refer to Chromium's BrowsingDataRemover interface.
实例属性
🌐 Instance Properties
Session 实例上可用的属性如下:
🌐 The following properties are available on instances of Session:
ses.availableSpellCheckerLanguages 只读
🌐 ses.availableSpellCheckerLanguages Readonly
一个 string[] 数组,其中包含所有已知可用的拼写检查语言。向 setSpellCheckerLanguages API 提供不在此数组中的语言代码将导致错误。
🌐 A string[] array which consists of all the known available spell checker languages. Providing a language
code to the setSpellCheckerLanguages API that isn't in this array will result in an error.
ses.spellCheckerEnabled
boolean 表示是否启用内置拼写检查器。
🌐 A boolean indicating whether builtin spell checker is enabled.
ses.storagePath 只读
🌐 ses.storagePath Readonly
string | null 表示用于在磁盘上持久存储此会话数据的绝对文件系统路径。对于内存中的会话,则返回 null。
🌐 A string | null indicating the absolute file system path where data for this
session is persisted on disk. For in memory sessions this returns null.
ses.cookies 只读
🌐 ses.cookies Readonly
此会话的 Cookies 对象。
🌐 A Cookies object for this session.
ses.extensions 只读
🌐 ses.extensions Readonly
此会话的 Extensions 对象。
🌐 A Extensions object for this session.
ses.serviceWorkers 只读
🌐 ses.serviceWorkers Readonly
此会话的 ServiceWorkers 对象。
🌐 A ServiceWorkers object for this session.
ses.webRequest 只读
🌐 ses.webRequest Readonly
此会话的 WebRequest 对象。
🌐 A WebRequest object for this session.
ses.protocol 只读
🌐 ses.protocol Readonly
此会话的 Protocol 对象。
🌐 A Protocol object for this session.
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 只读
🌐 ses.netLog Readonly
此会话的 NetLog 对象。
🌐 A NetLog object for this session.
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)
})