session
管理浏览器会话、cookie、缓存、代理设置等。
¥Manage browser sessions, cookies, cache, proxy settings, etc.
进程:主进程
¥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
字符串¥
partition
string
返回 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
字符串¥
path
string
返回 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
对象,应用的默认会话对象。
¥A Session
object, the default session object of the app.
类:会议
¥Class: Session
获取和设置会话的属性。
¥Get and set properties of a session.
进程:主进程
该类不是从 'electron'
模块导出的。它仅可用作 Electron API 中其他方法的返回值。
¥Process: Main
This class is not exported from the 'electron'
module. It is only available as a return value of other methods in the 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
:
事件:'will-download'
¥Event: 'will-download'
返回:
¥Returns:
-
event
事件¥
event
Event -
item
DownloadItem -
webContents
WebContents
当 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)
})
})
事件:'extension-loaded'
¥Event: 'extension-loaded'
返回:
¥Returns:
加载扩展后发出。每当将扩展添加到 "enabled" 扩展集时就会发生这种情况。这包括:
¥Emitted after an extension is loaded. This occurs whenever an extension is added to the "enabled" set of extensions. This includes:
-
正在从
Session.loadExtension
加载扩展。¥Extensions being loaded from
Session.loadExtension
. -
正在重新加载扩展:
¥Extensions being reloaded:
-
因车祸。
¥from a crash.
-
如果分机请求的话 (
chrome.runtime.reload()
)。¥if the extension requested it (
chrome.runtime.reload()
).
-
事件:'extension-unloaded'
¥Event: 'extension-unloaded'
返回:
¥Returns:
卸载扩展后发出。当调用 Session.removeExtension
时会发生这种情况。
¥Emitted after an extension is unloaded. This occurs when
Session.removeExtension
is called.
事件:'extension-ready'
¥Event: 'extension-ready'
返回:
¥Returns:
在加载扩展程序并初始化所有必要的浏览器状态以支持扩展程序后台页面的启动后发出。
¥Emitted after an extension is loaded and all necessary browser state is initialized to support the start of the extension's background page.
事件:'file-system-access-restricted'
¥Event: 'file-system-access-restricted'
返回:
¥Returns:
-
event
事件¥
event
Event -
details
对象¥
details
Object-
origin
字符串 - 发起对被阻止路径访问的来源。¥
origin
string - The origin that initiated access to the blocked path. -
isDirectory
布尔值 - 路径是否为目录。¥
isDirectory
boolean - Whether or not the path is a directory. -
path
字符串 - 试图访问的被阻止的路径。¥
path
string - The blocked path attempting to be accessed.
-
-
callback
函数¥
callback
Function-
action
字符串 - 由于限制路径访问尝试而采取的操作。¥
action
string - The action to take as a result of the restricted path access attempt.-
allow
- 这将允许尽管处于受限状态,但仍可以访问path
。¥
allow
- This will allowpath
to be accessed despite restricted status. -
deny
- 这将阻止访问请求并触发AbortError
。¥
deny
- This will block the access request and trigger anAbortError
. -
tryAgain
- 这将打开一个新的文件选择器并允许用户选择另一个路径。¥
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()
})
事件:'preconnect'
¥Event: 'preconnect'
返回:
¥Returns:
-
event
事件¥
event
Event -
preconnectUrl
字符串 - 渲染器请求预连接的 URL。¥
preconnectUrl
string - The URL being requested for preconnection by the renderer. -
allowCredentials
布尔值 - 如果渲染器请求连接包含凭据,则为 true(有关更多详细信息,请参阅 spec。)¥
allowCredentials
boolean - True if the renderer is requesting that the connection include credentials (see the spec for more details.)
当渲染进程请求预连接到 URL 时发出,通常是由于 资源提示。
¥Emitted when a render process requests preconnection to a URL, generally due to a resource hint.
事件:'spellcheck-dictionary-initialized'
¥Event: 'spellcheck-dictionary-initialized'
返回:
¥Returns:
-
event
事件¥
event
Event -
languageCode
字符串 - 词典文件的语言代码¥
languageCode
string - The language code of the dictionary file
当 hunspell 字典文件成功初始化时发出。下载文件后会发生这种情况。
¥Emitted when a hunspell dictionary file has been successfully initialized. This occurs after the file has been downloaded.
事件:'spellcheck-dictionary-download-begin'
¥Event: 'spellcheck-dictionary-download-begin'
返回:
¥Returns:
-
event
事件¥
event
Event -
languageCode
字符串 - 词典文件的语言代码¥
languageCode
string - The language code of the dictionary file
当 hunspell 字典文件开始下载时发出
¥Emitted when a hunspell dictionary file starts downloading
事件:'spellcheck-dictionary-download-success'
¥Event: 'spellcheck-dictionary-download-success'
返回:
¥Returns:
-
event
事件¥
event
Event -
languageCode
字符串 - 词典文件的语言代码¥
languageCode
string - The language code of the dictionary file
成功下载 hunspell 字典文件时发出
¥Emitted when a hunspell dictionary file has been successfully downloaded
事件:'spellcheck-dictionary-download-failure'
¥Event: 'spellcheck-dictionary-download-failure'
返回:
¥Returns:
-
event
事件¥
event
Event -
languageCode
字符串 - 词典文件的语言代码¥
languageCode
string - The language code of the dictionary file
当 hunspell 字典文件下载失败时发出。有关失败的详细信息,你应该收集网络日志并检查下载请求。
¥Emitted when a hunspell dictionary file download fails. For details on the failure you should collect a netlog and inspect the download request.
事件:'select-hid-device'
¥Event: 'select-hid-device'
返回:
¥Returns:
-
event
事件¥
event
Event -
details
对象¥
details
Object-
deviceList
HIDDevice[] -
frame
Web 框架主¥
frame
WebFrameMain
-
-
callback
函数¥
callback
Function-
deviceId
字符串 | 空(可选)¥
deviceId
string | null (optional)
-
当调用 navigator.hid.requestDevice
时需要选择 HID 设备时发出。应调用 callback
并选择 deviceId
;不向 callback
传递任何参数将取消请求。此外,可以使用 ses.setPermissionCheckHandler(handler)
和 ses.setDevicePermissionHandler(handler)
进一步管理 navigator.hid
上的权限。
¥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)
})
})
事件:'hid-device-added'
¥Event: 'hid-device-added'
返回:
¥Returns:
-
event
事件¥
event
Event -
details
对象¥
details
Object-
device
HID 设备¥
device
HIDDevice -
frame
Web 框架主¥
frame
WebFrameMain
-
如果在调用 select-hid-device
的回调之前有新设备可用,则在调用 navigator.hid.requestDevice
后发出,并且 select-hid-device
已触发。此事件旨在在使用 UI 要求用户选择设备时使用,以便可以使用新添加的设备更新 UI。
¥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.
事件:'hid-device-removed'
¥Event: 'hid-device-removed'
返回:
¥Returns:
-
event
事件¥
event
Event -
details
对象¥
details
Object-
device
HID 设备¥
device
HIDDevice -
frame
Web 框架主¥
frame
WebFrameMain
-
如果在调用 select-hid-device
的回调之前已删除设备,则在调用 navigator.hid.requestDevice
且 select-hid-device
已触发后发出。此事件适用于使用 UI 要求用户选择设备,以便更新 UI 以删除指定设备时使用。
¥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.
事件:'hid-device-revoked'
¥Event: 'hid-device-revoked'
返回:
¥Returns:
-
event
事件¥
event
Event -
details
对象¥
details
Object
调用 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.
事件:'select-serial-port'
¥Event: 'select-serial-port'
返回:
¥Returns:
-
event
事件¥
event
Event -
portList
SerialPort[] -
webContents
WebContents -
callback
函数¥
callback
Function-
portId
字符串¥
portId
string
-
当调用 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)
}
})
})
事件:'serial-port-added'
¥Event: 'serial-port-added'
返回:
¥Returns:
-
event
事件¥
event
Event -
port
SerialPort -
webContents
WebContents
如果在调用 select-serial-port
的回调之前有新的串行端口可用,则在调用 navigator.serial.requestPort
且 select-serial-port
已触发后发出。此事件旨在在使用 UI 要求用户选择端口时使用,以便可以使用新添加的端口更新 UI。
¥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.
事件:'serial-port-removed'
¥Event: 'serial-port-removed'
返回:
¥Returns:
-
event
事件¥
event
Event -
port
SerialPort -
webContents
WebContents
如果在调用 select-serial-port
的回调之前已删除串行端口,则在调用 navigator.serial.requestPort
且 select-serial-port
已触发后发出。此事件旨在在使用 UI 要求用户选择端口时使用,以便可以更新 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.
事件:'serial-port-revoked'
¥Event: 'serial-port-revoked'
返回:
¥Returns:
-
event
事件¥
event
Event -
details
对象¥
details
Object-
port
SerialPort -
frame
Web 框架主¥
frame
WebFrameMain -
origin
字符串 - 设备已被撤销的来源。¥
origin
string - The origin that the device has been revoked from.
-
调用 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()
}
事件:'select-usb-device'
¥Event: 'select-usb-device'
返回:
¥Returns:
-
event
事件¥
event
Event -
details
对象¥
details
Object-
deviceList
USBDevice[] -
frame
Web 框架主¥
frame
WebFrameMain
-
-
callback
函数¥
callback
Function-
deviceId
字符串(可选)¥
deviceId
string (optional)
-
当调用 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)
})
})
事件:'usb-device-added'
¥Event: 'usb-device-added'
返回:
¥Returns:
-
event
事件¥
event
Event -
device
USB 设备¥
device
USBDevice -
webContents
WebContents
如果在调用 select-usb-device
的回调之前有新设备可用,则在调用 navigator.usb.requestDevice
后发出,并且 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.
事件:'usb-device-removed'
¥Event: 'usb-device-removed'
返回:
¥Returns:
-
event
事件¥
event
Event -
device
USB 设备¥
device
USBDevice -
webContents
WebContents
如果在调用 select-usb-device
的回调之前已删除设备,则在调用 navigator.usb.requestDevice
且 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.
事件:'usb-device-revoked'
¥Event: 'usb-device-revoked'
返回:
¥Returns:
-
event
事件¥
event
Event -
details
对象¥
details
Object
调用 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
ProxyConfig
返回 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
字符串 - 要解析的主机名。¥
host
string - Hostname to resolve.
返回 Promise<ResolvedHost>
- 使用 host
的已解析 IP 地址进行解析。
¥Returns Promise<ResolvedHost>
- Resolves with the resolved IP addresses for the host
.
ses.resolveProxy(url)
url
URL
返回 Promise<string>
- 使用 url
的代理信息进行解析。
¥Returns Promise<string>
- Resolves with the proxy information for url
.
ses.forceReloadProxyConfig()
返回 Promise<void>
- 当重置代理服务的所有内部状态并重新应用最新的代理配置(如果已可用)时,将解决此问题。如果代理模式为 pac_script
,将再次从 pacScript
获取 pac 脚本。
¥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
字符串 - 下载位置。¥
path
string - The download location.
设置下载保存目录。默认情况下,下载目录将为相应应用文件夹下的 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.
注意:它将终止/失败当前正在进行的所有请求。
¥Note: It will terminate / fail all requests currently in flight.
ses.fetch(input[, init])
-
input
字符串 | GlobalRequest¥
input
string | GlobalRequest -
init
RequestInit & {绕过 CustomProtocolHandlers?:boolean } (optional)¥
init
RequestInit & { bypassCustomProtocolHandlers?: boolean } (optional)
返回 Promise<GlobalResponse>
- 见 响应。
¥Returns Promise<GlobalResponse>
- see Response.
使用 Chrome 的网络堆栈发送请求,类似于 fetch()
在渲染器中的工作方式。这与 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.
有关更多详细信息,请参阅 fetch()
的 MDN 文档。
¥See the MDN documentation for
fetch()
for more
details.
限制:
¥Limitations:
-
net.fetch()
不支持data:
或blob:
方案。¥
net.fetch()
does not support thedata:
orblob:
schemes. -
integrity
选项的值被忽略。¥The value of the
integrity
option is ignored. -
返回的
Response
对象的.type
和.url
值不正确。¥The
.type
and.url
values of the returnedResponse
object are incorrect.
默认情况下,使用 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
Function | null-
request
对象¥
request
Object-
hostname
字符串¥
hostname
string -
certificate
证书¥
certificate
Certificate -
validatedCertificate
证书¥
validatedCertificate
Certificate -
isIssuedByKnownRoot
布尔值 -true
(如果 Chromium 将根 CA 识别为标准根)。如果不是,则该证书可能是由其根已在本地安装的 MITM 代理生成的(例如,由公司代理)。如果verificationResult
不是OK
,则不应信任此信息。¥
isIssuedByKnownRoot
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
字符串 - 如果证书可信,则显示OK
,否则出现类似CERT_REVOKED
的错误。¥
verificationResult
string -OK
if the certificate is trusted, otherwise an error likeCERT_REVOKED
. -
errorCode
整数 - 错误代码。¥
errorCode
Integer - Error code.
-
-
callback
函数¥
callback
Function-
verificationResult
整数 - 值可以是 此处 中的证书错误代码之一。除了证书错误代码之外,还可以使用以下特殊代码。¥
verificationResult
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
- 表示成功并禁用证书透明度验证。¥
0
- Indicates success and disables Certificate Transparency verification. -
-2
- 表示失败。¥
-2
- Indicates failure. -
-3
- 使用来自 Chromium 的验证结果。¥
-3
- Uses the verification result from chromium.
-
-
-
设置 session
的证书验证过程,每当请求服务器证书验证时,将使用 proc(request, callback)
调用 proc
。调用 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)
}
})
注意:该过程的结果由网络服务缓存。
¥NOTE: The result of this procedure is cached by the network service.
ses.setPermissionRequestHandler(handler)
-
handler
Function | null-
webContents
WebContents - 请求许可的 WebContents。请注意,如果请求来自子帧,你应该使用requestingUrl
检查请求来源。¥
webContents
WebContents - WebContents requesting the permission. Please note that if the request comes from a subframe you should userequestingUrl
to check the request origin. -
permission
字符串 - 请求的权限的类型。¥
permission
string - The type of requested permission.-
clipboard-read
- 请求访问以从剪贴板读取。¥
clipboard-read
- Request access to read from the clipboard. -
clipboard-sanitized-write
- 请求写入剪贴板的权限。¥
clipboard-sanitized-write
- Request access to write to the clipboard. -
display-capture
- 通过 屏幕截图 API 请求访问以捕获屏幕。¥
display-capture
- Request access to capture the screen via the Screen Capture API. -
fullscreen
- 通过 全屏 API 请求控制应用的全屏状态。¥
fullscreen
- Request control of the app's fullscreen state via the Fullscreen API. -
geolocation
- 通过 地理定位 API 请求访问用户的位置¥
geolocation
- Request access to the user's location via the Geolocation API -
idle-detection
- 通过 空闲检测器 API 请求访问用户的空闲状态。¥
idle-detection
- Request access to the user's idle state via the IdleDetector API. -
media
- 请求访问媒体设备,例如摄像头、麦克风和扬声器。¥
media
- Request access to media devices such as camera, microphone and speakers. -
mediaKeySystem
- 请求访问受 DRM 保护的内容。¥
mediaKeySystem
- Request access to DRM protected content. -
midi
- 请求 网络 MIDI API 中的 MIDI 访问。¥
midi
- Request MIDI access in the Web MIDI API. -
midiSysex
- 请求使用 网络 MIDI API 中的系统独占消息。¥
midiSysex
- Request the use of system exclusive messages in the Web MIDI API. -
notifications
- 请求创建通知并能够使用 通知 API 在用户的系统托盘中显示它们¥
notifications
- Request notification creation and the ability to display them in the user's system tray using the Notifications API -
pointerLock
- 请求通过 指针锁 API 直接将鼠标移动解释为输入法。这些请求似乎总是源自主机。¥
pointerLock
- Request to directly interpret mouse movements as an input method via the Pointer Lock API. These requests always appear to originate from the main frame. -
keyboardLock
- 通过 Keyboard Lock API 请求捕获物理键盘上任意或所有按键的按键操作。这些请求似乎总是源自主机。¥
keyboardLock
- Request capture of keypresses for any or all of the keys on the physical keyboard via the Keyboard Lock API. These requests always appear to originate from the main frame. -
openExternal
- 请求在外部应用中打开链接。¥
openExternal
- Request to open links in external applications. -
speaker-selection
- 请求通过 发言人选择权限策略 枚举和选择音频输出设备。¥
speaker-selection
- Request to enumerate and select audio output devices via the speaker-selection permissions policy. -
storage-access
- 允许在第三方上下文中加载的内容使用 存储访问 API.cookie 请求访问第三方 cookie。¥
storage-access
- Allows content loaded in a third-party context to request access to third-party cookies using the Storage Access API. -
top-level-storage-access
- 允许顶层站点代表来自使用 存储访问 API.0 的同一相关网站集中的另一个站点的嵌入内容请求第三方 cookie 访问。¥
top-level-storage-access
- Allow top-level sites to request third-party cookie access on behalf of embedded content originating from another site in the same related website set using the Storage Access API. -
window-management
- 使用getScreenDetails
API 请求访问枚举屏幕。¥
window-management
- Request access to enumerate screens using thegetScreenDetails
API. -
unknown
- 无法识别的权限请求。¥
unknown
- An unrecognized permission request. -
fileSystem
- 使用 文件系统 API 请求访问读、写和文件管理功能。¥
fileSystem
- Request access to read, write, and file management capabilities using the File System API.
-
-
callback
函数¥
callback
Function-
permissionGranted
布尔值 - 允许或拒绝该权限。¥
permissionGranted
boolean - Allow or deny the permission.
-
-
details
PermissionRequest | FilesystemPermissionRequest | MediaAccessPermissionRequest | OpenExternalPermissionRequest - 有关所请求的权限的其他信息。¥
details
PermissionRequest | FilesystemPermissionRequest | MediaAccessPermissionRequest | OpenExternalPermissionRequest - Additional information about the permission being requested.
-
设置可用于响应 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)
-
handler
Function<boolean> | null-
webContents
(WebContents | null) - WebContents 检查权限。请注意,如果请求来自子帧,你应该使用requestingUrl
检查请求来源。所有进行权限检查的跨源子框架都会将null
webContents 传递给此处理程序,而某些其他权限检查(例如notifications
检查)将始终通过null
。你应该使用embeddingOrigin
和requestingOrigin
来确定所属帧和请求帧分别位于哪个源。¥
webContents
(WebContents | null) - WebContents checking the permission. Please note that if the request comes from a subframe you should userequestingUrl
to check the request origin. All cross origin sub frames making permission checks will pass anull
webContents to this handler, while certain other permission checks such asnotifications
checks will always passnull
. You should useembeddingOrigin
andrequestingOrigin
to determine what origin the owning frame and the requesting frame are on respectively. -
permission
字符串 - 权限检查的类型。¥
permission
string - Type of permission check.-
clipboard-read
- 请求访问以从剪贴板读取。¥
clipboard-read
- Request access to read from the clipboard. -
clipboard-sanitized-write
- 请求写入剪贴板的权限。¥
clipboard-sanitized-write
- Request access to write to the clipboard. -
geolocation
- 通过 地理定位 API 访问用户的地理位置数据¥
geolocation
- Access the user's geolocation data via the Geolocation API -
fullscreen
- 通过 全屏 API 控制应用的全屏状态。¥
fullscreen
- Control of the app's fullscreen state via the Fullscreen API. -
hid
- 通过 WebHID API 访问 HID 协议来操作 HID 设备。¥
hid
- Access the HID protocol to manipulate HID devices via the WebHID API. -
idle-detection
- 通过 空闲检测器 API 访问用户的空闲状态。¥
idle-detection
- Access the user's idle state via the IdleDetector API. -
media
- 访问相机、麦克风和扬声器等媒体设备。¥
media
- Access to media devices such as camera, microphone and speakers. -
mediaKeySystem
- 访问受 DRM 保护的内容。¥
mediaKeySystem
- Access to DRM protected content. -
midi
- 在 网络 MIDI API 中启用 MIDI 访问。¥
midi
- Enable MIDI access in the Web MIDI API. -
midiSysex
- 使用 网络 MIDI API 中的系统独占消息。¥
midiSysex
- Use system exclusive messages in the Web MIDI API. -
notifications
- 使用 通知 API 配置并向用户显示桌面通知。¥
notifications
- Configure and display desktop notifications to the user with the Notifications API. -
openExternal
- 在外部应用中打开链接。¥
openExternal
- Open links in external applications. -
pointerLock
- 通过 指针锁 API 直接将鼠标移动解释为输入法。这些请求似乎总是源自主机。¥
pointerLock
- Directly interpret mouse movements as an input method via the Pointer Lock API. These requests always appear to originate from the main frame. -
serial
- 使用 网络串行 API 读取和写入串行设备。¥
serial
- Read from and write to serial devices with the Web Serial API. -
storage-access
- 允许在第三方上下文中加载的内容使用 存储访问 API.cookie 请求访问第三方 cookie。¥
storage-access
- Allows content loaded in a third-party context to request access to third-party cookies using the Storage Access API. -
top-level-storage-access
- 允许顶层站点代表来自使用 存储访问 API.0 的同一相关网站集中的另一个站点的嵌入内容请求第三方 cookie 访问。¥
top-level-storage-access
- Allow top-level sites to request third-party cookie access on behalf of embedded content originating from another site in the same related website set using the Storage Access API. -
usb
- 使用 网络 USB API 将非标准通用串行总线 (USB) 兼容设备服务公开到网络。¥
usb
- Expose non-standard Universal Serial Bus (USB) compatible devices services to the web with the WebUSB API.
-
-
requestingOrigin
字符串 - 权限检查的原始 URL¥
requestingOrigin
string - The origin URL of the permission check -
details
对象 - 某些属性仅适用于某些权限类型。¥
details
Object - Some properties are only available on certain permission types.-
embeddingOrigin
字符串(可选) - 嵌入进行权限检查的框架的框架的起源。仅为进行权限检查的跨源子框架设置。¥
embeddingOrigin
string (optional) - The origin of the frame embedding the frame that made the permission check. Only set for cross-origin sub frames making permission checks. -
securityOrigin
字符串(可选) -media
检查的安全来源。¥
securityOrigin
string (optional) - The security origin of themedia
check. -
mediaType
字符串(可选) - 请求的媒体访问类型可以是video
、audio
或unknown
¥
mediaType
string (optional) - The type of media access being requested, can bevideo
,audio
orunknown
-
requestingUrl
字符串(可选) - 请求框架加载的最后一个 URL。不为进行权限检查的跨源子框架提供此功能。¥
requestingUrl
string (optional) - The last URL the requesting frame loaded. This is not provided for cross-origin sub frames making permission checks. -
isMainFrame
布尔值 - 发出请求的框架是否为主框架¥
isMainFrame
boolean - Whether the frame making the request is the main frame
-
-
设置可用于响应 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('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 | null-
request
对象¥
request
Object-
frame
Web 框架主 - 请求访问媒体的框架。¥
frame
WebFrameMain - Frame that is requesting access to media. -
securityOrigin
字符串 - 发出请求的页面的来源。¥
securityOrigin
String - Origin of the page making the request. -
videoRequested
Boolean - 如果 Web 内容请求视频流,则为 true。¥
videoRequested
Boolean - true if the web content requested a video stream. -
audioRequested
Boolean - 如果 Web 内容请求音频流,则为 true。¥
audioRequested
Boolean - true if the web content requested an audio stream. -
userGesture
Boolean - 触发此请求时用户手势是否处于活动状态。¥
userGesture
Boolean - Whether a user gesture was active when this request was triggered.
-
-
callback
函数¥
callback
Function-
streams
对象¥
streams
Object-
video
Object | Web 框架主 (optional)¥
video
Object | WebFrameMain (optional)-
id
字符串 - 被授予的流的 ID。这通常来自 桌面捕获源 对象。¥
id
String - The id of the stream being granted. This will usually come from a DesktopCapturerSource object. -
name
字符串 - 被授予的流的名称。这通常来自 桌面捕获源 对象。¥
name
String - The name of the stream being granted. This will usually come from a DesktopCapturerSource object.
-
-
audio
字符串| Web 框架主(可选) - 如果指定了字符串,则可以是loopback
或loopbackWithMute
。指定环回设备将捕获系统音频,目前仅在 Windows 上支持。如果指定了 WebFrameMain,将从该帧捕获音频。¥
audio
String | WebFrameMain (optional) - If a string is specified, can beloopback
orloopbackWithMute
. Specifying a loopback device will capture system audio, and is currently only supported on Windows. If a WebFrameMain is specified, will capture audio from that frame. -
enableLocalEcho
Boolean (optional) - 如果audio
是 Web 框架主 并且设置为true
,则音频的本地播放将不会静音(例如,使用MediaRecorder
录制WebFrameMain
并将此标志设置为true
将允许音频在录制时传递到扬声器)。默认为false
。¥
enableLocalEcho
Boolean (optional) - Ifaudio
is a WebFrameMain and this is set totrue
, then local playback of audio will not be muted (e.g. usingMediaRecorder
to recordWebFrameMain
with this flag set totrue
will allow audio to pass through to the speakers while recording). Default isfalse
.
-
-
-
-
opts
对象(可选)macOS 实验版¥
opts
Object (optional) macOS Experimental-
useSystemPicker
Boolean - 如果应使用可用的原生系统选择器,则为 true。默认为false
。macOS 实验版¥
useSystemPicker
Boolean - true if the available native system picker should be used. Default isfalse
. macOS Experimental
-
当 Web 内容请求通过 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
,则不会调用处理程序。
¥useSystemPicker
allows an application to use the system picker instead of providing a specific video source from getSources
.
This option is experimental, and currently available for MacOS 15+ only. If the system picker is available and useSystemPicker
is set to true
, the handler will not be invoked.
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 })
将 Web 框架主 对象作为视频或音频流传递将从该帧捕获视频或音频流。
¥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)
-
handler
Function<boolean> | null-
details
对象¥
details
Object-
deviceType
字符串 - 请求权限的设备类型可以是hid
、serial
或usb
。¥
deviceType
string - The type of device that permission is being requested on, can behid
,serial
, orusb
. -
origin
字符串 - 设备权限检查的原始 URL。¥
origin
string - The origin URL of the device permission check. -
device
HID 设备 | SerialPort | USB 设备 - 正在请求权限的设备。¥
device
HIDDevice | SerialPort | USBDevice - the device that permission is being requested for.
-
-
设置可用于响应 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)
-
handler
Function<string[]> | null-
details
对象¥
details
Object-
protectedClasses
字符串[] - 当前受保护的 USB 类别列表。可能的类值包括:¥
protectedClasses
string[] - The current list of protected USB classes. Possible class values include:-
audio
-
audio-video
-
hid
-
mass-storage
-
smart-card
-
video
-
wireless
-
-
-
设置可用于覆盖哪个 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:
-
audio
-
audio-video
-
hid
-
mass-storage
-
smart-card
-
video
-
wireless
从处理程序返回一个空字符串数组将允许所有 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
Function | null-
details
对象¥
details
Object-
deviceId
字符串¥
deviceId
string -
pairingKind
字符串 - 请求的配对提示的类型。以下值之一:¥
pairingKind
string - The type of pairing prompt being requested. One of the following values:-
confirm
此提示请求确认蓝牙设备应配对。¥
confirm
This prompt is requesting confirmation that the Bluetooth device should be paired. -
confirmPin
此提示请求确认所提供的 PIN 码与设备上显示的 PIN 码相符。¥
confirmPin
This prompt is requesting confirmation that the provided PIN matches the pin displayed on the device. -
providePin
此提示请求为设备提供 PIN。¥
providePin
This prompt is requesting that a pin be provided for the device.
-
-
frame
Web 框架主¥
frame
WebFrameMain -
pin
字符串(可选) - 用于验证pairingKind
是否为confirmPin
的引脚值。¥
pin
string (optional) - The pin value to verify ifpairingKind
isconfirmPin
.
-
-
callback
函数¥
callback
Function-
response
对象¥
response
Object-
confirmed
布尔值 - 如果取消对话框,则应传入false
。如果pairingKind
是confirm
或confirmPin
,则该值应指示配对是否已确认。如果pairingKind
是providePin
,则在提供值时该值应为true
。¥
confirmed
boolean -false
should be passed in if the dialog is canceled. If thepairingKind
isconfirm
orconfirmPin
, this value should indicate if the pairing is confirmed. If thepairingKind
isprovidePin
the value should betrue
when a value is provided. -
pin
字符串 | 空(可选) - 当pairingKind
为providePin
时,该值应该是蓝牙设备所需的引脚。¥
pin
string | null (optional) - When thepairingKind
isprovidePin
this value should be the required pin for the Bluetooth device.
-
-
-
设置处理程序以响应蓝牙配对请求。该处理程序允许开发者处理在配对前需要额外验证的设备。如果未定义处理程序,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 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>
- 操作完成后解决。
¥Returns Promise<void>
- Resolves when the operation is complete.
清除主机解析器缓存。
¥Clears the host resolver cache.
ses.allowNTLMCredentialsForDomains(domains)
-
domains
字符串 - 启用集成身份验证的服务器的逗号分隔列表。¥
domains
string - A comma-separated list of servers for which integrated authentication is enabled.
动态设置是否始终发送 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
字符串¥
userAgent
string -
acceptLanguages
字符串(可选)¥
acceptLanguages
string (optional)
覆盖此会话的 userAgent
和 acceptLanguages
。
¥Overrides the userAgent
and acceptLanguages
for this session.
acceptLanguages
必须是逗号分隔的语言代码有序列表,例如 "en-US,fr,de,ko,zh-CN,ja"
。
¥The acceptLanguages
must 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
- 此会话是否是持久会话。BrowserWindow
的默认 webContents
会话是持久的。从分区创建会话时,前缀为 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
对象¥
config
Object-
minVersion
字符串(可选) - 可以是tls1
、tls1.1
、tls1.2
或tls1.3
。连接到远程服务器时允许的最低 SSL 版本。默认为tls1
。¥
minVersion
string (optional) - Can betls1
,tls1.1
,tls1.2
ortls1.3
. The minimum SSL version to allow when connecting to remote servers. Defaults totls1
. -
maxVersion
字符串(可选) - 可以是tls1.2
或tls1.3
。连接到远程服务器时允许的最大 SSL 版本。默认为tls1.3
。¥
maxVersion
string (optional) - Can betls1.2
ortls1.3
. The maximum SSL version to allow when connecting to remote servers. Defaults totls1.3
. -
disabledCipherSuites
Integer[] (optional) - 除了网络内置策略禁用的密码套件之外,还应明确阻止使用的密码套件列表。支持的字面量形式:0xAABB,其中 AA 是cipher_suite[0]
,BB 是cipher_suite[1]
,如 RFC 2246 第 7.4.1.2 节中所定义。这种形式的无法识别但可解析的密码套件不会返回错误。前任:要禁用 TLS_RSA_WITH_RC4_128_MD5,请指定 0x0004,要禁用 TLS_ECDH_ECDSA_WITH_RC4_128_SHA,请指定 0xC002。请注意,无法使用此机制禁用 TLSv1.3 密码。¥
disabledCipherSuites
Integer[] (optional) - List of cipher suites which should be explicitly prevented from being used in addition to those disabled by the net built-in policy. Supported literal forms: 0xAABB, where AA iscipher_suite[0]
and BB iscipher_suite[1]
, as defined in RFC 2246, Section 7.4.1.2. Unrecognized but parsable cipher suites in this form will not return an error. Ex: To disable TLS_RSA_WITH_RC4_128_MD5, specify 0x0004, while to disable TLS_ECDH_ECDSA_WITH_RC4_128_SHA, specify 0xC002. Note that TLSv1.3 ciphers cannot be disabled using this mechanism.
-
设置会话的 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。¥
identifier
string - Valid UUID.
返回 Promise<Buffer>
- 使用 blob 数据进行解析。
¥Returns Promise<Buffer>
- resolves with blob data.
ses.downloadURL(url[, options])
-
url
字符串¥
url
string
启动 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
不同,这不会执行与页面来源相关的任何安全检查。
¥Note: This does not perform any security checks that relate to a page's origin,
unlike 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)
-
preloads
字符串[] - 预加载脚本的绝对路径数组¥
preloads
string[] - An array of absolute path to preload scripts
添加将在正常 preload
脚本运行之前在与此会话关联的所有 Web 内容上执行的脚本。
¥Adds scripts that will be executed on ALL web contents that are associated with
this session just before normal preload
scripts run.
ses.getPreloads()
返回 string[]
已注册的预加载脚本的路径数组。
¥Returns string[]
an array of paths to preload scripts that have been
registered.
ses.setCodeCachePath(path)
-
path
字符串 - 存储渲染器生成的 v8 JS 代码缓存的绝对路径。¥
path
String - Absolute path to store the v8 generated JS code cache from the renderer.
设置存储本次会话生成的 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.setSpellCheckerEnabled(enable)
-
enable
布尔值¥
enable
boolean
设置是否启用内置拼写检查器。
¥Sets whether to enable the builtin spell checker.
ses.isSpellCheckerEnabled()
返回 boolean
- 是否启用内置拼写检查器。
¥Returns boolean
- Whether the builtin spell checker is enabled.
ses.setSpellCheckerLanguages(languages)
-
languages
字符串[] - 用于启用拼写检查器的语言代码数组。¥
languages
string[] - An array of language codes to enable the spellchecker for.
内置的拼写检查器不会自动检测用户输入的语言。为了让拼写检查器正确检查单词,你必须使用一组语言代码调用此 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 上是无操作的。
¥Note: On macOS the OS spellchecker is used and will detect your language automatically. This API is a no-op on 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 将返回操作系统配置的任何语言。
¥Note: On macOS the OS spellchecker is used and has its own list of languages. On macOS, this API will return whichever languages have been configured by the OS.
ses.setSpellCheckerDictionaryDownloadURL(url)
-
url
字符串 - Electron 用于下载 hunspell 词典的基本 URL。¥
url
string - A base URL for Electron to download hunspell dictionaries from.
默认情况下,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 上,使用操作系统拼写检查器,因此我们不下载任何字典文件。此 API 在 macOS 上是无操作的。
¥Note: On macOS the OS spellchecker is used and therefore we do not download any dictionary files. This API is a no-op on macOS.
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
字符串 - 你要添加到词典中的单词¥
word
string - The word you want to add to the dictionary
返回 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 10 上,该单词也将写入操作系统自定义词典
¥Note: On macOS and Windows 10 this word will be written to the OS custom dictionary as well
ses.removeWordFromSpellCheckerDictionary(word)
-
word
字符串 - 你要从词典中删除的单词¥
word
string - The word you want to remove from the dictionary
返回 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 10 上,该单词也将从操作系统自定义词典中删除
¥Note: On macOS and Windows 10 this word will be removed from the OS custom dictionary as well
ses.loadExtension(path[, options])
-
path
字符串 - 包含解压的 Chrome 扩展程序的目录路径¥
path
string - Path to a directory containing an unpacked Chrome extension
返回 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。有关支持内容的更多详细信息,请参阅 支持的扩展 API。
¥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。
¥Note: This API cannot be called before the ready
event of the app
module
is emitted.
注意:不支持将扩展加载到内存中(非持久)会话中,并且会引发错误。
¥Note: Loading extensions into in-memory (non-persistent) sessions is not supported and will throw an error.
ses.removeExtension(extensionId)
-
extensionId
字符串 - 要删除的扩展 ID¥
extensionId
string - ID of extension to remove
卸载扩展。
¥Unloads an extension.
注意:在 app
模块的 ready
事件发出之前,无法调用此 API。
¥Note: This API cannot be called before the ready
event of the app
module
is emitted.
ses.getExtension(extensionId)
-
extensionId
字符串 - 查询分机 ID¥
extensionId
string - ID of extension to query
返回 Extension | null
- 具有给定 ID 的已加载扩展。
¥Returns Extension | null
- The loaded extension with the given ID.
注意:在 app
模块的 ready
事件发出之前,无法调用此 API。
¥Note: This API cannot be called before the ready
event of the app
module
is emitted.
ses.getAllExtensions()
返回 Extension[]
- 所有加载的扩展的列表。
¥Returns Extension[]
- A list of all loaded extensions.
注意:在 app
模块的 ready
事件发出之前,无法调用此 API。
¥Note: This API cannot be called before the ready
event of the app
module
is emitted.
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 的存储范围比来源更广。当删除 cookies 并通过 origins
(或 excludeOrigins
)进行过滤时,cookie 将在 可注册域名 级别被删除。例如,清除源 https://really.specific.origin.example.com/
的 cookie 将最终清除 example.com
的所有 cookie。清除来源 https://my.website.example.co.uk/
的 cookie 最终将清除 example.co.uk
的所有 cookie。
¥Note: Cookies are stored at a broader scope than origins. When removing cookies and filtering by origins
(or excludeOrigins
), the cookies will be removed at the registrable domain level. For example, clearing cookies for the origin https://really.specific.origin.example.com/
will end up clearing all cookies for example.com
. Clearing cookies for the origin https://my.website.example.co.uk/
will end up clearing all cookies for example.co.uk
.
有关更多信息,请参阅 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.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)
})