session
管理瀏覽器會話、cookie、快取、代理設定等。
處理程序:主要
session
模組可用於建立新的 Session
物件。
您也可以透過使用 WebContents
的 session
屬性,或從 session
模組存取現有頁面的 session
。
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ width: 800, height: 600 })
win.loadURL('https://github.com')
const ses = win.webContents.session
console.log(ses.getUserAgent())
方法
session
模組具有以下方法
session.fromPartition(partition[, options])
partition
字串
回傳 Session
- 來自 partition
字串的會話實例。當存在具有相同 partition
的現有 Session
時,將會回傳;否則,將使用 options
建立新的 Session
實例。
如果 partition
以 persist:
開頭,則頁面將使用應用程式中所有具有相同 partition
的頁面都可用的持續性會話。如果沒有 persist:
前綴,則頁面將使用記憶體內會話。如果 partition
為空,則會回傳應用程式的預設會話。
若要使用 options
建立 Session
,您必須確保先前從未使用過具有 partition
的 Session
。沒有辦法變更現有 Session
物件的 options
。
session.fromPath(path[, options])
path
字串
回傳 Session
- 來自 path
字串指定的絕對路徑的會話實例。當存在具有相同絕對路徑的現有 Session
時,將會回傳;否則,將使用 options
建立新的 Session
實例。如果路徑不是絕對路徑,則呼叫會擲回錯誤。此外,如果提供空字串,也會擲回錯誤。
若要使用 options
建立 Session
,您必須確保先前從未使用過具有 path
的 Session
。沒有辦法變更現有 Session
物件的 options
。
屬性
session
模組具有以下屬性
session.defaultSession
一個 Session
物件,應用程式的預設會話物件。
類別:Session
取得並設定會話的屬性。
處理程序:主要
此類別不會從 'electron'
模組匯出。它僅作為 Electron API 中其他方法的回傳值提供。
您可以在 session
模組中建立 Session
物件
const { session } = require('electron')
const ses = session.fromPartition('persist:name')
console.log(ses.getUserAgent())
實例事件
下列事件可在 Session
的實例上使用
事件:'will-download'
回傳
event
事件item
DownloadItemwebContents
WebContents
當 Electron 即將在 webContents
中下載 item
時發出。
呼叫 event.preventDefault()
將取消下載,而且 item
將無法從處理程序的下一個 tick 取得。
const { session } = require('electron')
session.defaultSession.on('will-download', (event, item, webContents) => {
event.preventDefault()
require('got')(item.getURL()).then((response) => {
require('node:fs').writeFileSync('/somewhere', response.body)
})
})
事件:'extension-loaded'
回傳
event
事件extension
Extension
在載入擴充功能後發出。每當將擴充功能新增至「已啟用」的擴充功能集時,就會發生這種情況。這包括
- 從
Session.loadExtension
載入的擴充功能。 - 重新載入的擴充功能
- 從當機。
- 如果擴充功能要求 (
chrome.runtime.reload()
)。
事件:'extension-unloaded'
回傳
event
事件extension
Extension
在卸載擴充功能後發出。當呼叫 Session.removeExtension
時,就會發生這種情況。
事件:'extension-ready'
回傳
event
事件extension
Extension
在載入擴充功能且已初始化所有必要的瀏覽器狀態以支援擴充功能的背景頁面啟動後發出。
事件:'file-system-access-restricted'
回傳
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()
})
事件:'preconnect'
回傳
event
事件preconnectUrl
字串 - 渲染器要求預先連線的 URL。allowCredentials
布林值 - 如果渲染器要求連線包含憑證 (如需更多詳細資料,請參閱 規格),則為 True。
當渲染程序要求預先連線到 URL 時發出,通常是因為 資源提示。
事件:'spellcheck-dictionary-initialized'
回傳
event
事件languageCode
字串 - 字典檔案的語言代碼
在成功初始化 hunspell 字典檔案時發出。這會在下載檔案後發生。
事件:'spellcheck-dictionary-download-begin'
回傳
event
事件languageCode
字串 - 字典檔案的語言代碼
當 hunspell 字典檔案開始下載時發出
事件:'spellcheck-dictionary-download-success'
回傳
event
事件languageCode
字串 - 字典檔案的語言代碼
當成功下載 hunspell 字典檔案時發出
事件:'spellcheck-dictionary-download-failure'
回傳
event
事件languageCode
字串 - 字典檔案的語言代碼
當 Hunspell 字典檔案下載失敗時發出。關於失敗的詳細資訊,您應該收集一個 netlog 並檢查下載請求。
事件:'select-hid-device'
回傳
event
事件details
物件deviceList
HIDDevice[]frame
WebFrameMain | null - 啟動此事件的框架。如果在框架導航或銷毀後存取,可能為null
。
callback
函式deviceId
string | null (選用)
當呼叫 navigator.hid.requestDevice
時,需要選擇 HID 裝置時發出。應使用要選擇的 deviceId
呼叫 callback
;不向 callback
傳遞任何參數將取消請求。此外,可以使用 ses.setPermissionCheckHandler(handler)
和 ses.setDevicePermissionHandler(handler)
來進一步管理 navigator.hid
上的權限。
const { app, BrowserWindow } = require('electron')
let win = null
app.whenReady().then(() => {
win = new BrowserWindow()
win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
if (permission === 'hid') {
// Add logic here to determine if permission should be given to allow HID selection
return true
}
return false
})
// Optionally, retrieve previously persisted devices from a persistent store
const grantedDevices = fetchGrantedDevices()
win.webContents.session.setDevicePermissionHandler((details) => {
if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'hid') {
if (details.device.vendorId === 123 && details.device.productId === 345) {
// Always allow this type of device (this allows skipping the call to `navigator.hid.requestDevice` first)
return true
}
// Search through the list of devices that have previously been granted permission
return grantedDevices.some((grantedDevice) => {
return grantedDevice.vendorId === details.device.vendorId &&
grantedDevice.productId === details.device.productId &&
grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber
})
}
return false
})
win.webContents.session.on('select-hid-device', (event, details, callback) => {
event.preventDefault()
const selectedDevice = details.deviceList.find((device) => {
return device.vendorId === 9025 && device.productId === 67
})
callback(selectedDevice?.deviceId)
})
})
事件:'hid-device-added'
回傳
event
事件details
物件device
HIDDeviceframe
WebFrameMain | null - 啟動此事件的框架。如果在框架導航或銷毀後存取,可能為null
。
在呼叫 navigator.hid.requestDevice
且 select-hid-device
發出後,如果在 select-hid-device
的回呼被呼叫之前有新裝置可用時發出。此事件旨在用於當使用 UI 要求使用者選擇裝置時,以便 UI 可以使用新加入的裝置更新。
事件:'hid-device-removed'
回傳
event
事件details
物件device
HIDDeviceframe
WebFrameMain | null - 啟動此事件的框架。如果在框架導航或銷毀後存取,可能為null
。
在呼叫 navigator.hid.requestDevice
且 select-hid-device
發出後,如果在 select-hid-device
的回呼被呼叫之前有裝置被移除時發出。此事件旨在用於當使用 UI 要求使用者選擇裝置時,以便 UI 可以更新以移除指定的裝置。
事件:'hid-device-revoked'
回傳
event
事件details
物件device
HIDDeviceorigin
string (選用) - 裝置被撤銷的來源。
在呼叫 HIDDevice.forget()
後發出。當使用 setDevicePermissionHandler
時,此事件可用於幫助維護權限的持久性儲存。
事件:'select-serial-port'
回傳
event
事件portList
SerialPort[]webContents
WebContentscallback
函式portId
string
當呼叫 navigator.serial.requestPort
時,需要選擇序列埠時發出。應使用要選擇的 portId
呼叫 callback
,向 callback
傳遞空字串將取消請求。此外,可以使用帶有 serial
權限的 ses.setPermissionCheckHandler(handler) 來管理 navigator.serial
上的權限。
const { app, BrowserWindow } = require('electron')
let win = null
app.whenReady().then(() => {
win = new BrowserWindow({
width: 800,
height: 600
})
win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
if (permission === 'serial') {
// Add logic here to determine if permission should be given to allow serial selection
return true
}
return false
})
// Optionally, retrieve previously persisted devices from a persistent store
const grantedDevices = fetchGrantedDevices()
win.webContents.session.setDevicePermissionHandler((details) => {
if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'serial') {
if (details.device.vendorId === 123 && details.device.productId === 345) {
// Always allow this type of device (this allows skipping the call to `navigator.serial.requestPort` first)
return true
}
// Search through the list of devices that have previously been granted permission
return grantedDevices.some((grantedDevice) => {
return grantedDevice.vendorId === details.device.vendorId &&
grantedDevice.productId === details.device.productId &&
grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber
})
}
return false
})
win.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
event.preventDefault()
const selectedPort = portList.find((device) => {
return device.vendorId === '9025' && device.productId === '67'
})
if (!selectedPort) {
callback('')
} else {
callback(selectedPort.portId)
}
})
})
事件:'serial-port-added'
回傳
event
事件port
SerialPortwebContents
WebContents
在呼叫 navigator.serial.requestPort
且 select-serial-port
發出後,如果在 select-serial-port
的回呼被呼叫之前有新序列埠可用時發出。此事件旨在用於當使用 UI 要求使用者選擇埠時,以便 UI 可以使用新加入的埠更新。
事件:'serial-port-removed'
回傳
event
事件port
SerialPortwebContents
WebContents
在呼叫 navigator.serial.requestPort
且 select-serial-port
發出後,如果在 select-serial-port
的回呼被呼叫之前有序列埠被移除時發出。此事件旨在用於當使用 UI 要求使用者選擇埠時,以便 UI 可以更新以移除指定的埠。
事件:'serial-port-revoked'
回傳
event
事件details
物件port
SerialPortframe
WebFrameMain | null - 啟動此事件的框架。如果在框架導航或銷毀後存取,可能為null
。origin
string - 裝置被撤銷的來源。
在呼叫 SerialPort.forget()
後發出。當使用 setDevicePermissionHandler
時,此事件可用於幫助維護權限的持久性儲存。
// Browser Process
const { app, BrowserWindow } = require('electron')
app.whenReady().then(() => {
const win = new BrowserWindow({
width: 800,
height: 600
})
win.webContents.session.on('serial-port-revoked', (event, details) => {
console.log(`Access revoked for serial device from origin ${details.origin}`)
})
})
// Renderer Process
const portConnect = async () => {
// Request a port.
const port = await navigator.serial.requestPort()
// Wait for the serial port to open.
await port.open({ baudRate: 9600 })
// ...later, revoke access to the serial port.
await port.forget()
}
事件:'select-usb-device'
回傳
event
事件details
物件deviceList
USBDevice[]frame
WebFrameMain | null - 啟動此事件的框架。如果在框架導航或銷毀後存取,可能為null
。
callback
函式deviceId
string (選用)
當呼叫 navigator.usb.requestDevice
時,需要選擇 USB 裝置時發出。應使用要選擇的 deviceId
呼叫 callback
;不向 callback
傳遞任何參數將取消請求。此外,可以使用 ses.setPermissionCheckHandler(handler)
和 ses.setDevicePermissionHandler(handler)
來進一步管理 navigator.usb
上的權限。
const { app, BrowserWindow } = require('electron')
let win = null
app.whenReady().then(() => {
win = new BrowserWindow()
win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
if (permission === 'usb') {
// Add logic here to determine if permission should be given to allow USB selection
return true
}
return false
})
// Optionally, retrieve previously persisted devices from a persistent store (fetchGrantedDevices needs to be implemented by developer to fetch persisted permissions)
const grantedDevices = fetchGrantedDevices()
win.webContents.session.setDevicePermissionHandler((details) => {
if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'usb') {
if (details.device.vendorId === 123 && details.device.productId === 345) {
// Always allow this type of device (this allows skipping the call to `navigator.usb.requestDevice` first)
return true
}
// Search through the list of devices that have previously been granted permission
return grantedDevices.some((grantedDevice) => {
return grantedDevice.vendorId === details.device.vendorId &&
grantedDevice.productId === details.device.productId &&
grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber
})
}
return false
})
win.webContents.session.on('select-usb-device', (event, details, callback) => {
event.preventDefault()
const selectedDevice = details.deviceList.find((device) => {
return device.vendorId === 9025 && device.productId === 67
})
if (selectedDevice) {
// Optionally, add this to the persisted devices (updateGrantedDevices needs to be implemented by developer to persist permissions)
grantedDevices.push(selectedDevice)
updateGrantedDevices(grantedDevices)
}
callback(selectedDevice?.deviceId)
})
})
事件:'usb-device-added'
回傳
event
事件device
USBDevicewebContents
WebContents
在呼叫 navigator.usb.requestDevice
且 select-usb-device
發出後,如果在 select-usb-device
的回呼被呼叫之前有新裝置可用時發出。此事件旨在用於當使用 UI 要求使用者選擇裝置時,以便 UI 可以使用新加入的裝置更新。
事件:'usb-device-removed'
回傳
event
事件device
USBDevicewebContents
WebContents
在呼叫 navigator.usb.requestDevice
且 select-usb-device
發出後,如果在 select-usb-device
的回呼被呼叫之前有裝置被移除時發出。此事件旨在用於當使用 UI 要求使用者選擇裝置時,以便 UI 可以更新以移除指定的裝置。
事件:'usb-device-revoked'
回傳
event
事件details
物件device
USBDeviceorigin
string (選用) - 裝置被撤銷的來源。
在呼叫 USBDevice.forget()
後發出。當使用 setDevicePermissionHandler
時,此事件可用於幫助維護權限的持久性儲存。
實例方法
以下方法在 Session
的實例上可用
ses.getCacheSize()
返回 Promise<Integer>
- 會話目前的快取大小,以位元組為單位。
ses.clearCache()
返回 Promise<void>
- 快取清除操作完成時解析。
清除會話的 HTTP 快取。
ses.clearStorageData([options])
返回 Promise<void>
- 儲存資料清除時解析。
ses.flushStorageData()
將任何未寫入的 DOMStorage 資料寫入磁碟。
ses.setProxy(config)
config
ProxyConfig
返回 Promise<void>
- Proxy 設定過程完成時解析。
設定 Proxy 設定。
您可能需要 ses.closeAllConnections
來關閉目前正在傳輸的連線,以防止將先前 Proxy 使用的集區 Socket 重複用於未來的請求。
ses.resolveHost(host, [options])
host
string - 要解析的主機名稱。
返回 Promise<ResolvedHost> - 使用 host
的已解析 IP 位址解析。
ses.resolveProxy(url)
url
URL
返回 Promise<string>
- 使用 url
的 Proxy 資訊解析。
ses.forceReloadProxyConfig()
返回 Promise<void>
- 當 Proxy 服務的所有內部狀態重設,且最新的 Proxy 設定已可用的話,則重新套用時解析。如果 Proxy 模式為 pac_script
,則將再次從 pacScript
擷取 pac 腳本。
ses.setDownloadPath(path)
path
string - 下載位置。
設定下載儲存目錄。依預設,下載目錄將位於各自應用程式資料夾下的 Downloads
。
ses.enableNetworkEmulation(options)
針對 session
,模擬具有指定組態的網路。
const win = new BrowserWindow()
// To emulate a GPRS connection with 50kbps throughput and 500 ms latency.
win.webContents.session.enableNetworkEmulation({
latency: 500,
downloadThroughput: 6400,
uploadThroughput: 6400
})
// To emulate a network outage.
win.webContents.session.enableNetworkEmulation({ offline: true })
ses.preconnect(options)
預先連線指定數量的 Socket 到一個來源。
ses.closeAllConnections()
傳回 Promise<void>
- 當所有連線都關閉時解析。
注意: 它將終止/失敗目前正在進行中的所有請求。
ses.fetch(input[, init])
input
字串 | GlobalRequestinit
RequestInit & { bypassCustomProtocolHandlers?: boolean } (選用)
傳回 Promise<GlobalResponse>
- 請參閱 Response。
使用 Chrome 的網路堆疊發送請求,類似於渲染器中 fetch()
的運作方式。這與使用 Node.js HTTP 堆疊的 Node 的 fetch()
不同。
範例
async function example () {
const response = await net.fetch('https://my.app')
if (response.ok) {
const body = await response.json()
// ... use the result.
}
}
另請參閱 net.fetch()
,這是一個方便的方法,用於從預設工作階段發出請求。
請參閱 MDN 文件中關於 fetch()
的更多詳細資訊。
限制
net.fetch()
不支援data:
或blob:
協定。integrity
選項的值將被忽略。- 傳回的
Response
物件的.type
和.url
值不正確。
預設情況下,使用 net.fetch
發出的請求可以發送到自訂協定以及 file:
,並且如果存在,將觸發 webRequest 處理程序。當 RequestInit 中設定了非標準的 bypassCustomProtocolHandlers
選項時,不會針對此請求呼叫自訂協定處理程序。這允許將攔截到的請求轉發到內建處理程序。當繞過自訂協定時,仍會觸發 webRequest 處理程序。
protocol.handle('https', (req) => {
if (req.url === 'https://my-app.com') {
return new Response('<body>my app</body>')
} else {
return net.fetch(req, { bypassCustomProtocolHandlers: true })
}
})
ses.disableNetworkEmulation()
停用已為 session
啟用的任何網路模擬。重置為原始網路組態。
ses.setCertificateVerifyProc(proc)
proc
函式 | nullrequest
物件hostname
字串certificate
CertificatevalidatedCertificate
CertificateisIssuedByKnownRoot
布林值 - 如果 Chromium 將根 CA 識別為標準根,則為true
。如果不是,則可能的情況是此憑證是由 MITM 代理產生,其根憑證已在本地安裝(例如,由公司代理安裝)。如果verificationResult
不是OK
,則不應信任此憑證。verificationResult
字串 - 如果憑證受信任,則為OK
,否則會出現類似CERT_REVOKED
的錯誤。errorCode
整數 - 錯誤代碼。
callback
函式verificationResult
整數 - 值可以是來自這裡的憑證錯誤代碼之一。除了憑證錯誤代碼之外,還可以使用以下特殊代碼。0
- 表示成功並停用憑證透明度驗證。-2
- 表示失敗。-3
- 使用來自 Chromium 的驗證結果。
為 session
設定憑證驗證程序,每當請求伺服器憑證驗證時,將使用 proc(request, callback)
呼叫 proc
。呼叫 callback(0)
接受憑證,呼叫 callback(-2)
拒絕憑證。
呼叫 setCertificateVerifyProc(null)
將還原為預設憑證驗證程序。
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
win.webContents.session.setCertificateVerifyProc((request, callback) => {
const { hostname } = request
if (hostname === 'github.com') {
callback(0)
} else {
callback(-2)
}
})
注意: 此程序的結果由網路服務快取。
ses.setPermissionRequestHandler(handler)
handler
函式 | nullwebContents
WebContents - 請求權限的 WebContents。請注意,如果請求來自子框架,您應該使用requestingUrl
來檢查請求來源。permission
字串 - 請求的權限類型。clipboard-read
- 請求從剪貼簿讀取的權限。clipboard-sanitized-write
- 請求寫入剪貼簿的權限。display-capture
- 請求透過 螢幕擷取 API 擷取螢幕的權限。fullscreen
- 請求透過 全螢幕 API 控制應用程式全螢幕狀態的權限。geolocation
- 請求透過 地理位置 API 存取使用者位置的權限。idle-detection
- 請求透過 IdleDetector API 存取使用者閒置狀態的權限。media
- 請求存取媒體裝置 (例如攝影機、麥克風和揚聲器) 的權限。mediaKeySystem
- 請求存取受 DRM 保護的內容的權限。midi
- 請求在 Web MIDI API 中存取 MIDI 的權限。midiSysex
- 請求在 Web MIDI API 中使用系統專屬訊息的權限。notifications
- 請求使用 通知 API 建立通知並將其顯示在使用者系統匣中的能力。pointerLock
- 請求透過 指標鎖定 API 直接將滑鼠移動解釋為輸入方式的權限。這些請求總是來自主框架。keyboardLock
- 請求透過 鍵盤鎖定 API 擷取實體鍵盤上任何或所有按鍵的按鍵事件的權限。這些請求總是來自主框架。openExternal
- 請求在外部應用程式中開啟連結的權限。speaker-selection
- 請求透過 speaker-selection 權限原則列舉和選取音訊輸出裝置的權限。storage-access
- 允許在第三方環境中載入的內容使用 儲存空間存取 API 請求存取第三方 Cookie。top-level-storage-access
- 允許頂層網站代表使用 儲存空間存取 API 的相同相關網站集中,來自其他網站的嵌入內容請求第三方 Cookie 存取權限。window-management
- 請求使用getScreenDetails
API 列舉螢幕的權限。unknown
- 未辨識的權限請求。fileSystem
- 請求使用 檔案系統 API 存取讀取、寫入和檔案管理功能的權限。
callback
函式permissionGranted
布林值 - 允許或拒絕權限。
details
PermissionRequest | FilesystemPermissionRequest | MediaAccessPermissionRequest | OpenExternalPermissionRequest - 關於請求權限的其他資訊。
設定可用於回應 session
權限請求的處理程序。呼叫 callback(true)
將允許該權限,而 callback(false)
將拒絕該權限。若要清除處理程序,請呼叫 setPermissionRequestHandler(null)
。請注意,您還必須實作 setPermissionCheckHandler
才能獲得完整的權限處理。大多數 Web API 都會執行權限檢查,然後在檢查被拒絕時發出權限請求。
const { session } = require('electron')
session.fromPartition('some-partition').setPermissionRequestHandler((webContents, permission, callback) => {
if (webContents.getURL() === 'some-host' && permission === 'notifications') {
return callback(false) // denied.
}
callback(true)
})
ses.setPermissionCheckHandler(handler)
handler
Function<boolean> | nullwebContents
(WebContents | null) - 檢查權限的 WebContents。請注意,如果請求來自子框架,您應該使用requestingUrl
來檢查請求來源。所有進行權限檢查的跨來源子框架都會將null
webContents 傳遞給此處理程序,而某些其他權限檢查 (例如notifications
檢查) 將始終傳遞null
。您應該使用embeddingOrigin
和requestingOrigin
來判斷擁有框架和請求框架分別位於哪個來源。permission
字串 - 權限檢查的類型。clipboard-read
- 請求從剪貼簿讀取的權限。clipboard-sanitized-write
- 請求寫入剪貼簿的權限。geolocation
- 透過 地理位置 API 存取使用者的地理位置資料。fullscreen
- 透過 全螢幕 API 控制應用程式的全螢幕狀態。hid
- 透過 WebHID API 存取 HID 協定以操作 HID 裝置。idle-detection
- 透過 IdleDetector API 存取使用者的閒置狀態。media
- 存取媒體裝置,例如相機、麥克風和喇叭。mediaKeySystem
- 存取 DRM 保護的內容。midi
- 在 Web MIDI API 中啟用 MIDI 存取。midiSysex
- 在 Web MIDI API 中使用系統專屬訊息。notifications
- 使用 Notifications API 設定並向使用者顯示桌面通知。openExternal
- 在外部應用程式中開啟連結。pointerLock
- 透過 Pointer Lock API 將滑鼠移動直接解譯為輸入方式。這些請求一律源自主框架。serial
- 使用 Web Serial API 讀取和寫入序列裝置。storage-access
- 允許在第三方環境中載入的內容使用 儲存空間存取 API 請求存取第三方 Cookie。top-level-storage-access
- 允許頂層網站代表使用 儲存空間存取 API 的相同相關網站集中,來自其他網站的嵌入內容請求第三方 Cookie 存取權限。usb
- 使用 WebUSB API 將非標準通用序列匯流排 (USB) 相容裝置服務公開給網頁。
requestingOrigin
string - 權限檢查的來源 URLdetails
Object - 某些屬性僅在特定權限類型上可用。embeddingOrigin
string (選用) - 進行權限檢查的框架所嵌入之框架的來源。僅針對進行權限檢查的跨來源子框架設定。securityOrigin
string (選用) -media
檢查的安全來源。mediaType
string (選用) - 要求的媒體存取類型,可以是video
、audio
或unknown
requestingUrl
string (選用) - 請求框架載入的最後一個 URL。不會為進行權限檢查的跨來源子框架提供此 URL。isMainFrame
boolean - 發出請求的框架是否為主框架
設定處理程式,可用於回應 session
的權限檢查。傳回 true
將允許權限,而傳回 false
將拒絕權限。請注意,您還必須實作 setPermissionRequestHandler
才能取得完整的權限處理。大多數 Web API 會先進行權限檢查,然後在檢查遭到拒絕時提出權限要求。若要清除處理程式,請呼叫 setPermissionCheckHandler(null)
。
const { session } = require('electron')
const url = require('url')
session.fromPartition('some-partition').setPermissionCheckHandler((webContents, permission, requestingOrigin) => {
if (new URL(requestingOrigin).hostname === 'some-host' && permission === 'notifications') {
return true // granted
}
return false // denied
})
ses.setDisplayMediaRequestHandler(handler[, opts])
handler
函式 | nullrequest
物件frame
WebFrameMain | null - 請求存取媒體的框架。如果在框架導覽或銷毀後存取,則可能為null
。securityOrigin
String - 發出請求的頁面來源。videoRequested
Boolean - 如果網頁內容要求視訊串流,則為 true。audioRequested
Boolean - 如果網頁內容要求音訊串流,則為 true。userGesture
Boolean - 觸發此請求時是否有使用者手勢處於活動狀態。
callback
函式streams
Objectvideo
Object | WebFrameMain (選用)id
String - 授予的串流 ID。通常來自 DesktopCapturerSource 物件。name
String - 授予的串流名稱。通常來自 DesktopCapturerSource 物件。
audio
String | WebFrameMain (選用) - 如果指定字串,則可以是loopback
或loopbackWithMute
。指定迴路裝置將擷取系統音訊,目前僅在 Windows 上支援。如果指定 WebFrameMain,將擷取該框架的音訊。enableLocalEcho
Boolean (選用) - 如果audio
是 WebFrameMain 且此設定為true
,則不會將音訊的本機播放設為靜音(例如,使用MediaRecorder
錄製WebFrameMain
,且此旗標設定為true
將允許音訊在錄製時傳遞到喇叭)。預設值為false
。
opts
Object (選用) macOS 實驗性useSystemPicker
Boolean - 如果應使用可用的原生系統選擇器,則為 true。預設值為false
。 macOS 實驗性
當網頁內容透過 navigator.mediaDevices.getDisplayMedia
API 要求存取顯示媒體時,將會呼叫此處理程式。使用 desktopCapturer API 選擇要授予存取權的串流。
useSystemPicker
允許應用程式使用系統選擇器,而不是提供來自 getSources
的特定視訊來源。此選項為實驗性,目前僅適用於 MacOS 15+。如果系統選擇器可用且 useSystemPicker
設定為 true
,則不會叫用處理程式。
const { session, desktopCapturer } = require('electron')
session.defaultSession.setDisplayMediaRequestHandler((request, callback) => {
desktopCapturer.getSources({ types: ['screen'] }).then((sources) => {
// Grant access to the first screen found.
callback({ video: sources[0] })
})
// Use the system picker if available.
// Note: this is currently experimental. If the system picker
// is available, it will be used and the media request handler
// will not be invoked.
}, { useSystemPicker: true })
將 WebFrameMain 物件當作視訊或音訊串流傳遞,將擷取該框架的視訊或音訊串流。
const { session } = require('electron')
session.defaultSession.setDisplayMediaRequestHandler((request, callback) => {
// Allow the tab to capture itself.
callback({ video: request.frame })
})
傳遞 null
而不是函式,會將處理程式重設為預設狀態。
ses.setDevicePermissionHandler(handler)
handler
Function<boolean> | nulldetails
物件deviceType
string - 正在請求權限的裝置類型,可以是hid
、serial
或usb
。origin
string - 裝置權限檢查的來源 URL。device
HIDDevice | SerialPort | USBDevice - 正在請求權限的裝置。
設定處理程式,可用於回應 session
的裝置權限檢查。傳回 true
將允許裝置,而傳回 false
將拒絕裝置。若要清除處理程式,請呼叫 setDevicePermissionHandler(null)
。此處理程式可用於為裝置提供預設權限,而無需先呼叫裝置權限(例如透過 navigator.hid.requestDevice
)。如果未定義此處理程式,則會使用透過裝置選擇(例如透過 navigator.hid.requestDevice
)授予的預設裝置權限。此外,Electron 的預設行為是將授予的裝置權限儲存在記憶體中。如果需要長期儲存,開發人員可以儲存授予的裝置權限(例如在處理 select-hid-device
事件時),然後使用 setDevicePermissionHandler
從該儲存體讀取。
const { app, BrowserWindow } = require('electron')
let win = null
app.whenReady().then(() => {
win = new BrowserWindow()
win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
if (permission === 'hid') {
// Add logic here to determine if permission should be given to allow HID selection
return true
} else if (permission === 'serial') {
// Add logic here to determine if permission should be given to allow serial port selection
} else if (permission === 'usb') {
// Add logic here to determine if permission should be given to allow USB device selection
}
return false
})
// Optionally, retrieve previously persisted devices from a persistent store
const grantedDevices = fetchGrantedDevices()
win.webContents.session.setDevicePermissionHandler((details) => {
if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'hid') {
if (details.device.vendorId === 123 && details.device.productId === 345) {
// Always allow this type of device (this allows skipping the call to `navigator.hid.requestDevice` first)
return true
}
// Search through the list of devices that have previously been granted permission
return grantedDevices.some((grantedDevice) => {
return grantedDevice.vendorId === details.device.vendorId &&
grantedDevice.productId === details.device.productId &&
grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber
})
} else if (details.deviceType === 'serial') {
if (details.device.vendorId === 123 && details.device.productId === 345) {
// Always allow this type of device (this allows skipping the call to `navigator.hid.requestDevice` first)
return true
}
}
return false
})
win.webContents.session.on('select-hid-device', (event, details, callback) => {
event.preventDefault()
const selectedDevice = details.deviceList.find((device) => {
return device.vendorId === 9025 && device.productId === 67
})
callback(selectedDevice?.deviceId)
})
})
ses.setUSBProtectedClassesHandler(handler)
handler
Function<string[]> | nulldetails
物件protectedClasses
string[] - 目前受保護的 USB 類別清單。可能的類別值包括audio
audio-video
hid
mass-storage
smart-card
video
wireless
設定處理程式,可用於覆寫哪些 USB 類別受到保護。處理程式的傳回值是一個字串陣列,其中包含應視為受保護(例如,在渲染器中不可用)的 USB 類別。陣列的有效值為
audio
audio-video
hid
mass-storage
smart-card
video
wireless
從處理程式傳回空的字串陣列將允許所有 USB 類別;傳回傳入的陣列將維護受保護 USB 類別的預設清單(如果未定義處理程式,這也是預設行為)。若要清除處理程式,請呼叫 setUSBProtectedClassesHandler(null)
。
const { app, BrowserWindow } = require('electron')
let win = null
app.whenReady().then(() => {
win = new BrowserWindow()
win.webContents.session.setUSBProtectedClassesHandler((details) => {
// Allow all classes:
// return []
// Keep the current set of protected classes:
// return details.protectedClasses
// Selectively remove classes:
return details.protectedClasses.filter((usbClass) => {
// Exclude classes except for audio classes
return usbClass.indexOf('audio') === -1
})
})
})
ses.setBluetoothPairingHandler(handler)
Windows Linux
handler
函式 | nulldetails
物件deviceId
stringpairingKind
string - 要求的配對提示類型。下列其中一個值confirm
此提示要求確認是否應配對藍牙裝置。confirmPin
此提示要求確認提供的 PIN 碼是否與裝置上顯示的 PIN 碼相符。providePin
此提示要求為裝置提供 PIN 碼。
frame
WebFrameMain | null - 啟動此處理程式的框架。如果在框架導覽或銷毀後存取,則可能為null
。pin
string (選用) - 如果pairingKind
為confirmPin
,則要驗證的 PIN 碼值。
callback
函式response
Objectconfirmed
boolean - 如果對話方塊已取消,則應傳入false
。如果pairingKind
為confirm
或confirmPin
,此值應指出是否已確認配對。如果pairingKind
為providePin
,則當提供值時,此值應為true
。pin
string | null (選用) - 當pairingKind
為providePin
時,此值應為藍牙裝置所需的 PIN 碼。
設定處理程式以回應藍牙配對要求。此處理程式允許開發人員處理在配對前需要額外驗證的裝置。如果未定義處理程式,則 Linux 或 Windows 上任何需要額外驗證的配對都會自動取消。macOS 不需要處理程式,因為 macOS 會自動處理配對。若要清除處理程式,請呼叫 setBluetoothPairingHandler(null)
。
const { app, BrowserWindow, session } = require('electron')
const path = require('node:path')
function createWindow () {
let bluetoothPinCallback = null
const mainWindow = new BrowserWindow({
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
mainWindow.webContents.session.setBluetoothPairingHandler((details, callback) => {
bluetoothPinCallback = callback
// Send a IPC message to the renderer to prompt the user to confirm the pairing.
// Note that this will require logic in the renderer to handle this message and
// display a prompt to the user.
mainWindow.webContents.send('bluetooth-pairing-request', details)
})
// Listen for an IPC message from the renderer to get the response for the Bluetooth pairing.
mainWindow.webContents.ipc.on('bluetooth-pairing-response', (event, response) => {
bluetoothPinCallback(response)
})
}
app.whenReady().then(() => {
createWindow()
})
ses.clearHostResolverCache()
傳回 Promise<void>
- 在操作完成時解析。
清除主機解析器快取。
ses.allowNTLMCredentialsForDomains(domains)
domains
string - 啟用整合式驗證的伺服器清單,以逗號分隔。
動態設定是否始終傳送 HTTP NTLM 或 Negotiate 驗證的認證。
const { session } = require('electron')
// consider any url ending with `example.com`, `foobar.com`, `baz`
// for integrated authentication.
session.defaultSession.allowNTLMCredentialsForDomains('*example.com, *foobar.com, *baz')
// consider all urls for integrated authentication.
session.defaultSession.allowNTLMCredentialsForDomains('*')
ses.setUserAgent(userAgent[, acceptLanguages])
userAgent
stringacceptLanguages
string (選用)
覆寫此工作階段的 userAgent
和 acceptLanguages
。
acceptLanguages
必須是語言代碼的逗號分隔的排序清單,例如 "en-US,fr,de,ko,zh-CN,ja"
。
這不會影響現有的 WebContents
,每個 WebContents
都可以使用 webContents.setUserAgent
來覆寫工作階段範圍的使用者代理程式。
ses.isPersistent()
傳回 boolean
- 此工作階段是否為永久工作階段。BrowserWindow
的預設 webContents
工作階段是永久的。從分割區建立工作階段時,以 persist:
為前綴的工作階段將是永久的,而其他工作階段將是暫時的。
ses.getUserAgent()
傳回 string
- 此工作階段的使用者代理程式。
ses.setSSLConfig(config)
config
ObjectminVersion
string (選用) - 可以是tls1
、tls1.1
、tls1.2
或tls1.3
。連線到遠端伺服器時允許的最低 SSL 版本。預設值為tls1
。maxVersion
字串 (選用) - 可以是tls1.2
或tls1.3
。連線至遠端伺服器時允許的最大 SSL 版本。預設值為tls1.3
。disabledCipherSuites
整數陣列 (選用) - 除了網路內建策略停用的密碼套件外,明確禁止使用的密碼套件清單。支援的文字形式:0xAABB,其中 AA 是cipher_suite[0]
,而 BB 是cipher_suite[1]
,如 RFC 2246 第 7.4.1.2 節所定義。此形式中無法辨識但可剖析的密碼套件不會傳回錯誤。例如:要停用 TLS_RSA_WITH_RC4_128_MD5,請指定 0x0004,而要停用 TLS_ECDH_ECDSA_WITH_RC4_128_SHA,請指定 0xC002。請注意,無法使用此機制停用 TLSv1.3 密碼。
設定工作階段的 SSL 設定。所有後續的網路請求都將使用新的設定。現有的網路連線 (例如 WebSocket 連線) 不會終止,但集區中的舊套接字不會重複用於新的連線。
ses.getBlobData(identifier)
identifier
字串 - 有效的 UUID。
傳回 Promise<Buffer>
- 以 blob 資料解析。
ses.downloadURL(url[, options])
url
字串
啟動 url
上資源的下載。API 將產生一個 DownloadItem,可以使用 will-download 事件存取。
注意:這不會執行任何與頁面來源相關的安全性檢查,與 webContents.downloadURL
不同。
ses.createInterruptedDownload(options)
允許從先前的 Session
恢復 cancelled
或 interrupted
的下載。API 將產生一個 DownloadItem,可以使用 will-download 事件存取。DownloadItem 不會與任何 WebContents
相關聯,初始狀態將為 interrupted
。只有在 DownloadItem 上呼叫 resume
API 時,才會開始下載。
ses.clearAuthCache()
傳回 Promise<void>
- 在清除工作階段的 HTTP 驗證快取時解析。
ses.setPreloads(preloads)
preloads
字串陣列 - 要預先載入的腳本的絕對路徑陣列
加入腳本,這些腳本將在與此工作階段相關聯的所有網頁內容上執行,就在正常的 preload
腳本執行之前。
ses.getPreloads()
傳回 string[]
已註冊的預先載入腳本路徑的陣列。
ses.setCodeCachePath(path)
path
字串 - 儲存來自渲染器的 v8 產生的 JS 程式碼快取的絕對路徑。
設定目錄以儲存此工作階段產生的 JS 程式碼快取。使用者不需要在此呼叫之前建立該目錄,如果該目錄不存在,則執行階段將建立該目錄,否則將使用現有的目錄。如果無法建立目錄,則不會使用程式碼快取,並且執行階段內所有與程式碼快取相關的操作都將會無聲地失敗。預設情況下,該目錄將是各自使用者資料夾下的 Code Cache
。
請注意,預設情況下,程式碼快取僅適用於 http(s) URL,若要為自訂協定啟用程式碼快取,則在註冊協定時必須指定 codeCache: true
和 standard: true
。
ses.clearCodeCaches(options)
傳回 Promise<void>
- 在程式碼快取清除操作完成時解析。
ses.getSharedDictionaryUsageInfo()
傳回 Promise<SharedDictionaryUsageInfo[]>
- Chromium 網路服務儲存中共享字典資訊條目的陣列。
共享字典用於為透過網路傳送的資料提供進階壓縮,特別是使用 Brotli 和 ZStandard。您無需在 Electron 中呼叫任何共享字典 API 即可使用此進階網頁功能,但如果您這麼做,它們可以更深入地控制和檢查解壓縮期間使用的共享字典。
若要取得特定共享字典條目的詳細資訊,請呼叫 getSharedDictionaryInfo(options)
。
ses.getSharedDictionaryInfo(options)
傳回 Promise<SharedDictionaryInfo[]>
- Chromium 網路服務儲存中共享字典資訊條目的陣列。
若要取得所有目前共享字典的資訊,請呼叫 getSharedDictionaryUsageInfo()
。
ses.clearSharedDictionaryCache()
傳回 Promise<void>
- 在清除記憶體和磁碟中的字典快取時解析。
ses.clearSharedDictionaryCacheForIsolationKey(options)
傳回 Promise<void>
- 在針對指定的隔離金鑰清除記憶體和磁碟中的字典快取時解析。
ses.setSpellCheckerEnabled(enable)
enable
布林值
設定是否啟用內建拼寫檢查器。
ses.isSpellCheckerEnabled()
傳回 boolean
- 是否啟用內建拼寫檢查器。
ses.setSpellCheckerLanguages(languages)
languages
字串陣列 - 要為其啟用拼寫檢查器的語言代碼陣列。
內建拼寫檢查器不會自動偵測使用者輸入的語言。為了讓拼寫檢查器正確檢查他們的單字,您必須使用語言代碼陣列呼叫此 API。您可以使用 ses.availableSpellCheckerLanguages
屬性取得支援的語言代碼清單。
注意:在 macOS 上,會使用 OS 拼寫檢查器,並會自動偵測您的語言。此 API 在 macOS 上是無作業的。
ses.getSpellCheckerLanguages()
傳回 string[]
- 為其啟用拼寫檢查器的語言代碼陣列。如果此清單為空白,則拼寫檢查器將會回復為使用 en-US
。預設情況下,如果啟動時此設定為空白清單,Electron 會嘗試使用目前的 OS 地區設定來填入此設定。此設定會在重新啟動時保留。
注意:在 macOS 上,會使用 OS 拼寫檢查器,並且它有自己的語言清單。在 macOS 上,此 API 將傳回 OS 設定的任何語言。
ses.setSpellCheckerDictionaryDownloadURL(url)
url
字串 - Electron 從中下載 hunspell 字典的基本 URL。
預設情況下,Electron 會從 Chromium CDN 下載 hunspell 字典。如果您想要覆寫此行為,可以使用此 API 將字典下載器指向您自己託管的 hunspell 字典版本。我們會隨著每個版本發布一個 hunspell_dictionaries.zip
檔案,其中包含您需要在此處託管的檔案。
檔案伺服器必須不區分大小寫。如果您無法做到這一點,您必須上傳每個檔案兩次:一次使用 ZIP 檔案中的大小寫,另一次使用全部小寫的檔案名稱。
如果 hunspell_dictionaries.zip
中存在的檔案可在 https://example.com/dictionaries/language-code.bdic
取得,則您應該使用 ses.setSpellCheckerDictionaryDownloadURL('https://example.com/dictionaries/')
呼叫此 API。請注意尾隨斜線。字典的 URL 形成為 ${url}${filename}
。
注意:在 macOS 上,會使用 OS 拼寫檢查器,因此我們不會下載任何字典檔案。此 API 在 macOS 上是無作業的。
ses.listWordsInSpellCheckerDictionary()
回傳 Promise<string[]>
- 應用程式自訂字典中所有單字的陣列。當完整字典從磁碟載入時解析。
ses.addWordToSpellCheckerDictionary(word)
word
string - 您想要加入字典的單字
回傳 boolean
- 單字是否成功寫入自訂字典。此 API 無法在非持久性(記憶體內)的會話中使用。
注意: 在 macOS 和 Windows 10 上,此單字也會寫入作業系統的自訂字典
ses.removeWordFromSpellCheckerDictionary(word)
word
string - 您想要從字典移除的單字
回傳 boolean
- 單字是否成功從自訂字典移除。此 API 無法在非持久性(記憶體內)的會話中使用。
注意: 在 macOS 和 Windows 10 上,此單字也會從作業系統的自訂字典移除
ses.loadExtension(path[, options])
path
string - 包含未壓縮 Chrome 擴充功能的目錄路徑
回傳 Promise<Extension>
- 當擴充功能載入時解析。
如果無法載入擴充功能,此方法會引發例外。如果在安裝擴充功能時有警告(例如,如果擴充功能請求 Electron 不支援的 API),則會記錄到主控台。
請注意,Electron 不支援所有 Chrome 擴充功能 API。有關支援內容的詳細資訊,請參閱支援的擴充功能 API。
請注意,在較早版本的 Electron 中,載入的擴充功能會記住以供應用程式將來執行。現在已非如此:如果您想要載入擴充功能,必須在每次啟動應用程式時呼叫 loadExtension
。
const { app, session } = require('electron')
const path = require('node:path')
app.whenReady().then(async () => {
await session.defaultSession.loadExtension(
path.join(__dirname, 'react-devtools'),
// allowFileAccess is required to load the devtools extension on file:// URLs.
{ allowFileAccess: true }
)
// Note that in order to use the React DevTools extension, you'll need to
// download and unzip a copy of the extension.
})
此 API 不支援載入壓縮的 (.crx) 擴充功能。
注意: 此 API 無法在發出 app
模組的 ready
事件之前呼叫。
注意: 不支援將擴充功能載入到記憶體內(非持久性)的會話中,並會擲回錯誤。
ses.removeExtension(extensionId)
extensionId
string - 要移除的擴充功能 ID
卸載擴充功能。
注意: 此 API 無法在發出 app
模組的 ready
事件之前呼叫。
ses.getExtension(extensionId)
extensionId
string - 要查詢的擴充功能 ID
回傳 Extension | null
- 具有指定 ID 的已載入擴充功能。
注意: 此 API 無法在發出 app
模組的 ready
事件之前呼叫。
ses.getAllExtensions()
回傳 Extension[]
- 所有已載入擴充功能的清單。
注意: 此 API 無法在發出 app
模組的 ready
事件之前呼叫。
ses.getStoragePath()
回傳 string | null
- 此會話的資料在磁碟上持續存在的絕對檔案系統路徑。對於記憶體內會話,此方法會回傳 null
。
ses.clearData([options])
回傳 Promise<void>
- 當所有資料都已清除時解析。
清除各種不同的資料類型。
此方法會清除更多類型的資料,並且比 clearStorageData
方法更徹底。
注意: Cookie 的儲存範圍比來源更廣。當移除 Cookie 並依 origins
(或 excludeOrigins
)篩選時,Cookie 會在 可註冊網域層級移除。例如,清除來源為 https://really.specific.origin.example.com/
的 Cookie,最終會清除 example.com
的所有 Cookie。清除來源為 https://my.website.example.co.uk/
的 Cookie,最終會清除 example.co.uk
的所有 Cookie。
注意: 清除快取資料也會清除共用字典快取。這表示用於壓縮的任何字典都可能會在清除快取後重新載入。如果您想要清除共用字典快取,但保留其他快取資料,則您可能會想要使用 clearSharedDictionaryCache
方法。
如需詳細資訊,請參閱 Chromium 的 BrowsingDataRemover
介面。
執行個體屬性
以下屬性可在 Session
的執行個體上使用
ses.availableSpellCheckerLanguages
唯讀
一個 string[]
陣列,其中包含所有已知的可用拼字檢查器語言。將此陣列中沒有的語言代碼提供給 setSpellCheckerLanguages
API 會導致錯誤。
ses.spellCheckerEnabled
一個 boolean
,指出是否啟用內建拼字檢查器。
ses.storagePath
唯讀
一個 string | null
,指出此會話的資料在磁碟上持續存在的絕對檔案系統路徑。對於記憶體內會話,此方法會回傳 null
。
ses.cookies
唯讀
此會話的 Cookies
物件。
ses.serviceWorkers
唯讀
此會話的 ServiceWorkers
物件。
ses.webRequest
唯讀
此會話的 WebRequest
物件。
ses.protocol
唯讀
此會話的 Protocol
物件。
const { app, session } = require('electron')
const path = require('node:path')
app.whenReady().then(() => {
const protocol = session.fromPartition('some-partition').protocol
if (!protocol.registerFileProtocol('atom', (request, callback) => {
const url = request.url.substr(7)
callback({ path: path.normalize(path.join(__dirname, url)) })
})) {
console.error('Failed to register protocol')
}
})
ses.netLog
唯讀
此會話的 NetLog
物件。
const { app, session } = require('electron')
app.whenReady().then(async () => {
const netLog = session.fromPartition('some-partition').netLog
netLog.startLogging('/path/to/net-log')
// After some network events
const path = await netLog.stopLogging()
console.log('Net-logs written to', path)
})