跳到主要內容

session

管理瀏覽器工作階段、Cookie、快取、Proxy 設定等等。

程序:主程序

session 模組可用於建立新的 Session 物件。

您也可以使用 WebContentssession 屬性,或從 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 字串
  • options 物件 (選用)

傳回 Session - 來自 partition 字串的工作階段實例。當存在具有相同 partition 的現有 Session 時,將傳回該實例;否則將使用 options 建立新的 Session 實例。

如果 partitionpersist: 開頭,則頁面將使用持續性工作階段,該工作階段適用於應用程式中具有相同 partition 的所有頁面。如果沒有 persist: 前綴,則頁面將使用記憶體內工作階段。如果 partition 為空,則將傳回應用程式的預設工作階段。

若要使用 options 建立 Session,您必須確保從未使用過具有 partitionSession。沒有辦法變更現有 Session 物件的 options

session.fromPath(path[, options])

  • path 字串
  • options 物件 (選用)

傳回 Session - 來自絕對路徑的工作階段實例,如 path 字串所指定。當存在具有相同絕對路徑的現有 Session 時,將傳回該實例;否則將使用 options 建立新的 Session 實例。如果路徑不是絕對路徑,則呼叫將擲回錯誤。此外,如果提供空字串,也會擲回錯誤。

若要使用 options 建立 Session,您必須確保從未使用過具有 pathSession。沒有辦法變更現有 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'

傳回

當 Electron 即將在 webContents 中下載 item 時發出。

呼叫 event.preventDefault() 將取消下載,且 item 將在程序的下一個刻度中不可用。

const { session } = require('electron')
session.defaultSession.on('will-download', (event, item, webContents) => {
event.preventDefault()
require('got')(item.getURL()).then((response) => {
require('node:fs').writeFileSync('/somewhere', response.body)
})
})

事件:'extension-loaded'

傳回

在擴充功能載入後發出。每當擴充功能新增至擴充功能的「已啟用」集合時,就會發生這種情況。這包括

  • Session.loadExtension 載入的擴充功能。
  • 正在重新載入的擴充功能

事件:'extension-unloaded'

傳回

在擴充功能卸載後發出。當呼叫 Session.removeExtension 時,就會發生這種情況。

事件:'extension-ready'

傳回

在擴充功能載入且所有必要的瀏覽器狀態都已初始化以支援擴充功能背景頁面的啟動後發出。

事件:'file-system-access-restricted'

傳回

  • event 事件
  • details 物件
    • origin 字串 - 啟動存取受阻路徑的來源。
    • isDirectory boolean - 路徑是否為目錄。
    • 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 boolean - 如果渲染程序要求連線包含憑證,則為 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 字串 | 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 HIDDevice
    • frame WebFrameMain | null - 啟動此事件的框架。如果在框架導航或被銷毀後存取,則可能為 null

在呼叫 navigator.hid.requestDevice 且在呼叫 select-hid-device 的回呼之前,如果有新裝置可用,則在 select-hid-device 觸發後發出。此事件旨在用於使用 UI 要求使用者選取裝置,以便可以使用新新增的裝置更新 UI。

事件:'hid-device-removed'

傳回

  • event 事件
  • details 物件
    • device HIDDevice
    • frame WebFrameMain | null - 啟動此事件的框架。如果在框架導航或被銷毀後存取,則可能為 null

在呼叫 navigator.hid.requestDevice 且在呼叫 select-hid-device 的回呼之前,如果裝置已移除,則在 select-hid-device 觸發後發出。此事件旨在用於使用 UI 要求使用者選取裝置,以便可以更新 UI 以移除指定的裝置。

事件:'hid-device-revoked'

傳回

  • event 事件
  • details 物件
    • device HIDDevice
    • origin 字串 (選用) - 裝置已撤銷的來源。

在呼叫 HIDDevice.forget() 後發出。當使用 setDevicePermissionHandler 時,此事件可用於協助維護權限的持續性儲存。

事件:'select-serial-port'

傳回

當呼叫 navigator.serial.requestPort 時,需要選取序列埠時發出。應使用要選取的 portId 呼叫 callback,將空字串傳遞給 callback 將取消請求。此外,可以使用 ses.setPermissionCheckHandler(handler)serial 權限來管理 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'

傳回

在呼叫 navigator.serial.requestPort 且在呼叫 select-serial-port 的回呼之前,如果有新的序列埠可用,則在 select-serial-port 觸發後發出。此事件旨在用於使用 UI 要求使用者選取埠,以便可以使用新新增的埠更新 UI。

事件:'serial-port-removed'

傳回

在呼叫 navigator.serial.requestPort 且在呼叫 select-serial-port 的回呼之前,如果序列埠已移除,則在 select-serial-port 觸發後發出。此事件旨在用於使用 UI 要求使用者選取埠,以便可以更新 UI 以移除指定的埠。

事件:'serial-port-revoked'

傳回

  • event 事件
  • details 物件
    • port SerialPort
    • frame WebFrameMain | null - 啟動此事件的框架。如果在框架導航或被銷毀後存取,則可能為 null
    • origin 字串 - 裝置已撤銷的來源。

在呼叫 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 字串 (選用)

當呼叫 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'

傳回

在呼叫 navigator.usb.requestDevice 且在呼叫 select-usb-device 的回呼之前,如果有新裝置可用,則在 select-usb-device 觸發後發出。此事件旨在用於使用 UI 要求使用者選取裝置,以便可以使用新新增的裝置更新 UI。

事件:'usb-device-removed'

傳回

在呼叫 navigator.usb.requestDevice 且在呼叫 select-usb-device 的回呼之前,如果裝置已移除,則在 select-usb-device 觸發後發出。此事件旨在用於使用 UI 要求使用者選取裝置,以便可以更新 UI 以移除指定的裝置。

事件:'usb-device-revoked'

傳回

  • event 事件
  • details 物件
    • device USBDevice
    • origin 字串 (選用) - 裝置已撤銷的來源。

在呼叫 USBDevice.forget() 後發出。當使用 setDevicePermissionHandler 時,此事件可用於協助維護權限的持續性儲存。

實例方法

以下方法在 Session 的實例上可用

ses.getCacheSize()

傳回 Promise<Integer> - 工作階段目前的快取大小,以位元組為單位。

ses.clearCache()

傳回 Promise<void> - 在快取清除作業完成時解析。

清除工作階段的 HTTP 快取。

ses.clearStorageData([options])

  • options 物件 (選用)
    • origin 字串 (選用) - 應遵循 window.location.origin 的表示法 scheme://host:port
    • storages string[] (選用) - 要清除的儲存類型,可以是 cookiesfilesystemindexdblocalstorageshadercachewebsqlserviceworkerscachestorage。如果未指定,則清除所有儲存類型。
    • quotas string[] (選用) - 要清除的配額類型,可以是 temporarysyncable。如果未指定,則清除所有配額。

傳回 Promise<void> - 在儲存資料已清除時解析。

ses.flushStorageData()

將任何未寫入的 DOMStorage 資料寫入磁碟。

ses.setProxy(config)

傳回 Promise<void> - 在 Proxy 設定程序完成時解析。

設定 Proxy 設定。

您可能需要 ses.closeAllConnections 來關閉目前正在進行中的連線,以防止集區 Socket 使用先前的 Proxy 被未來的請求重複使用。

ses.resolveHost(host, [options])

  • host 字串 - 要解析的主機名稱。
  • options 物件 (選用)
    • queryType 字串 (選用) - 要求的 DNS 查詢類型。如果未指定,解析器將根據 IPv4/IPv6 設定選取 A 或 AAAA (或兩者)
      • A - 僅提取 A 記錄
      • AAAA - 僅提取 AAAA 記錄。
    • source 字串 (選用) - 用於解析位址的來源。預設值允許解析器選取適當的來源。僅影響大型外部來源的使用 (例如,呼叫系統進行解析或使用 DNS)。即使指定了來源,結果仍然可以來自快取、解析「localhost」或 IP 常值等。下列值之一
      • any (預設) - 解析器將選取適當的來源。結果可能來自 DNS、MulticastDNS、HOSTS 檔案等
      • system - 結果僅會從系統或 OS 擷取,例如透過 getaddrinfo() 系統呼叫
      • dns - 結果僅來自 DNS 查詢
      • mdns - 結果僅來自 Multicast DNS 查詢
      • localOnly - 不會使用外部來源。結果僅來自快速本機來源,無論來源設定為何,這些來源都可用,例如快取、hosts 檔案、IP 常值解析等。
    • cacheUsage 字串 (選用) - 指出可以使用哪些 DNS 快取項目 (如果有的話) 來提供回應。下列值之一
      • allowed (預設) - 如果主機快取未過時,則結果可能來自主機快取
      • staleAllowed - 即使主機快取已過時 (因過期或網路變更),結果也可能來自主機快取
      • disallowed - 結果不會來自主機快取。
    • secureDnsPolicy 字串 (選用) - 控制解析器對此請求的安全 DNS 行為。下列值之一
      • allow (預設)
      • disable

傳回 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 字串 - 下載位置。

設定下載儲存目錄。依預設,下載目錄將是各自應用程式資料夾下的 Downloads

ses.enableNetworkEmulation(options)

  • options 物件
    • offline boolean (選用) - 是否模擬網路中斷。預設值為 false。
    • latency Double (選用) - RTT (毫秒)。預設值為 0,這將停用延遲節流。
    • downloadThroughput Double (選用) - 下載速率 (Bps)。預設值為 0,這將停用下載節流。
    • uploadThroughput Double (選用) - 上傳速率 (Bps)。預設值為 0,這將停用上傳節流。

模擬具有給定 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)

  • options 物件
    • url 字串 - 預先連線的 URL。只有來源與開啟 Socket 相關。
    • numSockets number (選用) - 要預先連線的 Socket 數量。必須介於 1 到 6 之間。預設值為 1。

將給定數量的 Socket 預先連線到來源。

ses.closeAllConnections()

傳回 Promise<void> - 在所有連線關閉時解析。

注意: 這將終止/失敗目前正在進行中的所有請求。

ses.fetch(input[, init])

傳回 Promise<GlobalResponse> - 請參閱 Response

傳送請求,類似於 fetch() 在渲染程序中的運作方式,使用 Chrome 的網路堆疊。這與 Node 的 fetch() 不同,Node 的 fetch() 使用 Node.js 的 HTTP 堆疊。

範例

async function example () {
const response = await net.fetch('https://my.app')
if (response.ok) {
const body = await response.json()
// ... use the result.
}
}

另請參閱 net.fetch(),這是一種便利方法,可從 預設工作階段 發出請求。

如需更多詳細資訊,請參閱 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 函數 | null
    • request 物件
      • hostname 字串
      • certificate Certificate
      • validatedCertificate Certificate
      • isIssuedByKnownRoot boolean - 如果 Chromium 將根 CA 識別為標準根,則為 true。如果不是,則可能是此憑證是由 MITM Proxy 產生,其根已在本機安裝 (例如,由公司 Proxy)。如果 verificationResult 不是 OK,則不應信任此憑證。
      • verificationResult 字串 - 如果憑證受信任,則為 OK,否則為錯誤,例如 CERT_REVOKED
      • errorCode Integer - 錯誤代碼。
    • callback 函數
      • verificationResult Integer - 值可以是 此處 的憑證錯誤代碼之一。除了憑證錯誤代碼之外,還可以使用以下特殊代碼。
        • 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 函數 | null
    • webContents WebContents - 請求權限的 WebContents。請注意,如果請求來自子框架,您應該使用 requestingUrl 來檢查請求來源。
    • permission 字串 - 要求的權限類型。
      • clipboard-read - 請求從剪貼簿讀取的權限。
      • clipboard-sanitized-write - 請求寫入剪貼簿的權限。
      • display-capture - 請求透過 Screen Capture API 擷取螢幕的權限。
      • fullscreen - 請求透過 Fullscreen API 控制應用程式全螢幕狀態的權限。
      • geolocation - 請求透過 Geolocation API 存取使用者位置的權限。
      • idle-detection - 請求透過 IdleDetector API 存取使用者閒置狀態的權限。
      • media - 請求存取媒體裝置,例如攝影機、麥克風和喇叭。
      • mediaKeySystem - 請求存取 DRM 保護的內容。
      • midi - 請求在 Web MIDI API 中存取 MIDI。
      • midiSysex - 請求在 Web MIDI API 中使用系統專屬訊息。
      • notifications - 請求建立通知以及使用 Notifications API 在使用者系統匣中顯示通知的功能。
      • pointerLock - 請求透過 Pointer Lock API 直接將滑鼠移動解譯為輸入方法。這些請求一律看似源自主框架。
      • keyboardLock - 請求透過 Keyboard Lock API 擷取實體鍵盤上任何或所有按鍵的按鍵輸入。這些請求一律看似源自主框架。
      • openExternal - 請求在外部應用程式中開啟連結。
      • speaker-selection - 請求透過 speaker-selection permissions policy 列舉和選取音訊輸出裝置。
      • storage-access - 允許在第三方環境中載入的內容使用 Storage Access API 請求存取第三方 Cookie。
      • top-level-storage-access - 允許頂層網站代表來自相同相關網站集中另一個網站的嵌入內容,請求第三方 Cookie 存取,使用 Storage Access API
      • window-management - 請求使用 getScreenDetails API 存取螢幕列舉。
      • unknown - 無法辨識的權限請求。
      • fileSystem - 請求使用 File System 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> | null
    • webContents (WebContents | null) - 檢查權限的 WebContents。請注意,如果請求來自子框架,您應該使用 requestingUrl 來檢查請求來源。所有發出權限檢查的跨來源子框架都會將 null webContents 傳遞給此處理常式,而某些其他權限檢查(例如 notifications 檢查)則一律會傳遞 null。您應該使用 embeddingOriginrequestingOrigin 來判斷擁有框架和請求框架分別位於哪個來源。
    • permission 字串 - 權限檢查類型。
      • clipboard-read - 請求從剪貼簿讀取的權限。
      • clipboard-sanitized-write - 請求寫入剪貼簿的權限。
      • geolocation - 透過 Geolocation API 存取使用者的地理位置資料。
      • fullscreen - 透過 Fullscreen API 控制應用程式的全螢幕狀態。
      • hid - 透過 WebHID API 存取 HID 協定以操控 HID 裝置。
      • idle-detection - 透過 IdleDetector API 存取使用者的閒置狀態。
      • media - 存取媒體裝置,例如攝影機、麥克風和喇叭。
      • mediaKeySystem - 存取 DRM 保護的內容。
      • midi - 在 Web MIDI API 中啟用 MIDI 存取。
      • midiSysex - 在 Web MIDI API 中使用系統專屬訊息。
      • notifications - 使用 Notifications API 設定和向使用者顯示桌面通知。
      • openExternal - 在外部應用程式中開啟連結。
      • pointerLock - 透過 Pointer Lock API 直接將滑鼠移動解譯為輸入方法。這些請求一律看似源自主框架。
      • serial - 使用 Web Serial API 從序列裝置讀取和寫入資料。
      • storage-access - 允許在第三方環境中載入的內容使用 Storage Access API 請求存取第三方 Cookie。
      • top-level-storage-access - 允許頂層網站代表來自相同相關網站集中另一個網站的嵌入內容,請求第三方 Cookie 存取,使用 Storage Access API
      • usb - 使用 WebUSB API 將非標準通用序列匯流排 (USB) 相容裝置服務公開給 Web。
      • deprecated-sync-clipboard-read 已停用 - 請求執行 document.execCommand("paste") 的權限
    • requestingOrigin 字串 - 權限檢查的來源 URL
    • details 物件 - 某些屬性僅適用於特定權限類型。
      • embeddingOrigin 字串 (選用) - 嵌入發出權限檢查框架的框架來源。僅針對發出權限檢查的跨來源子框架設定。
      • securityOrigin 字串 (選用) - media 檢查的安全性來源。
      • mediaType 字串 (選用) - 請求的媒體存取類型,可以是 videoaudiounknown
      • requestingUrl 字串 (選用) - 請求框架載入的最後一個 URL。不適用於發出權限檢查的跨來源子框架。
      • isMainFrame 布林值 - 發出請求的框架是否為主框架

設定處理常式,可用於回應 session 的權限檢查。傳回 true 將允許權限,而 false 將拒絕權限。請注意,您也必須實作 setPermissionRequestHandler 才能取得完整的權限處理。大多數 Web API 會先進行權限檢查,然後在檢查遭到拒絕時提出權限請求。若要清除處理常式,請呼叫 setPermissionCheckHandler(null)

const { session } = require('electron')
const url = require('url')
session.fromPartition('some-partition').setPermissionCheckHandler((webContents, permission, requestingOrigin) => {
if (new URL(requestingOrigin).hostname === 'some-host' && permission === 'notifications') {
return true // granted
}

return false // denied
})

ses.setDisplayMediaRequestHandler(handler[, opts])

  • handler 函數 | null
    • request 物件
      • frame WebFrameMain | null - 請求存取媒體的框架。如果在框架導覽或遭到終止後存取,則可能為 null
      • securityOrigin 字串 - 發出請求頁面的來源。
      • videoRequested 布林值 - 如果 Web 內容請求視訊串流,則為 true。
      • audioRequested 布林值 - 如果 Web 內容請求音訊串流,則為 true。
      • userGesture 布林值 - 觸發此請求時,使用者手勢是否處於活動狀態。
    • callback 函數
      • streams 物件
        • video 物件 | WebFrameMain (選用)
        • audio 字串 | WebFrameMain (選用) - 如果指定字串,則可以是 loopbackloopbackWithMute。指定迴路裝置將擷取系統音訊,目前僅在 Windows 上支援。如果指定 WebFrameMain,則將從該框架擷取音訊。
        • enableLocalEcho 布林值 (選用) - 如果 audioWebFrameMain 且此值設定為 true,則音訊的本機播放將不會靜音(例如,使用 MediaRecorder 錄製 WebFrameMain 時,如果此旗標設定為 true,則允許音訊在錄製時傳遞至喇叭)。預設值為 false
  • opts 物件 (選用) macOS 實驗性
    • useSystemPicker 布林值 - 如果應使用可用的原生系統選取器,則為 true。預設值為 falsemacOS 實驗性

當 Web 內容透過 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> | null
    • details 物件
      • deviceType 字串 - 正在請求權限的裝置類型,可以是 hidserialusb
      • origin 字串 - 裝置權限檢查的來源 URL。
      • device HIDDevice | SerialPort | USBDevice - 正在請求權限的裝置。

設定處理常式,可用於回應 session 的裝置權限檢查。傳回 true 將允許裝置獲得許可,而 false 將拒絕許可。若要清除處理常式,請呼叫 setDevicePermissionHandler(null)。此處理常式可用於為裝置提供預設權限,而無需先呼叫裝置權限(例如透過 navigator.hid.requestDevice)。如果未定義此處理常式,將使用透過裝置選取(例如透過 navigator.hid.requestDevice)授與的預設裝置權限。此外,Electron 的預設行為是將授與的裝置權限儲存在記憶體中。如果需要長期儲存,開發人員可以儲存授與的裝置權限(例如在處理 select-hid-device 事件時),然後使用 setDevicePermissionHandler 從該儲存空間讀取。

const { app, BrowserWindow } = require('electron')

let win = null

app.whenReady().then(() => {
win = new BrowserWindow()

win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
if (permission === 'hid') {
// Add logic here to determine if permission should be given to allow HID selection
return true
} else if (permission === 'serial') {
// Add logic here to determine if permission should be given to allow serial port selection
} else if (permission === 'usb') {
// Add logic here to determine if permission should be given to allow USB device selection
}
return false
})

// Optionally, retrieve previously persisted devices from a persistent store
const grantedDevices = fetchGrantedDevices()

win.webContents.session.setDevicePermissionHandler((details) => {
if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'hid') {
if (details.device.vendorId === 123 && details.device.productId === 345) {
// Always allow this type of device (this allows skipping the call to `navigator.hid.requestDevice` first)
return true
}

// Search through the list of devices that have previously been granted permission
return grantedDevices.some((grantedDevice) => {
return grantedDevice.vendorId === details.device.vendorId &&
grantedDevice.productId === details.device.productId &&
grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber
})
} else if (details.deviceType === 'serial') {
if (details.device.vendorId === 123 && details.device.productId === 345) {
// Always allow this type of device (this allows skipping the call to `navigator.hid.requestDevice` first)
return true
}
}
return false
})

win.webContents.session.on('select-hid-device', (event, details, callback) => {
event.preventDefault()
const selectedDevice = details.deviceList.find((device) => {
return device.vendorId === 9025 && device.productId === 67
})
callback(selectedDevice?.deviceId)
})
})

ses.setUSBProtectedClassesHandler(handler)

  • handler Function<string[]> | null
    • details 物件
      • protectedClasses 字串陣列 - 目前受保護的 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 函數 | null
    • details 物件
      • deviceId 字串
      • pairingKind 字串 - 請求的配對提示類型。下列其中一個值
        • confirm 此提示請求確認應配對藍牙裝置。
        • confirmPin 此提示請求確認提供的 PIN 碼與裝置上顯示的 PIN 碼相符。
        • providePin 此提示請求為裝置提供 PIN 碼。
      • frame WebFrameMain | null - 啟動此處理常式的框架。如果在框架導覽或遭到終止後存取,則可能為 null
      • pin 字串 (選用) - 如果 pairingKindconfirmPin,則為要驗證的 PIN 碼值。
    • callback 函數
      • response 物件
        • confirmed 布林值 - 如果對話方塊已取消,則應傳入 false。如果 pairingKindconfirmconfirmPin,則此值應指出是否已確認配對。如果 pairingKindprovidePin,則當提供值時,值應為 true
        • pin 字串 | null (選用) - 當 pairingKindprovidePin 時,此值應為藍牙裝置所需的 PIN 碼。

設定處理常式以回應藍牙配對請求。此處理常式允許開發人員處理需要額外驗證才能配對的裝置。當未定義處理常式時,Linux 或 Windows 上任何需要額外驗證的配對都會自動取消。macOS 不需要處理常式,因為 macOS 會自動處理配對。若要清除處理常式,請呼叫 setBluetoothPairingHandler(null)

const { app, BrowserWindow, session } = require('electron')
const path = require('node:path')

function createWindow () {
let bluetoothPinCallback = null

const mainWindow = new BrowserWindow({
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})

mainWindow.webContents.session.setBluetoothPairingHandler((details, callback) => {
bluetoothPinCallback = callback
// Send a IPC message to the renderer to prompt the user to confirm the pairing.
// Note that this will require logic in the renderer to handle this message and
// display a prompt to the user.
mainWindow.webContents.send('bluetooth-pairing-request', details)
})

// Listen for an IPC message from the renderer to get the response for the Bluetooth pairing.
mainWindow.webContents.ipc.on('bluetooth-pairing-response', (event, response) => {
bluetoothPinCallback(response)
})
}

app.whenReady().then(() => {
createWindow()
})

ses.clearHostResolverCache()

傳回 Promise<void> - 在作業完成時解析。

清除主機解析器快取。

ses.allowNTLMCredentialsForDomains(domains)

  • domains 字串 - 以逗號分隔的伺服器清單,已針對這些伺服器啟用整合式驗證。

動態設定是否一律傳送 HTTP NTLM 或 Negotiate 驗證的憑證。

const { session } = require('electron')
// consider any url ending with `example.com`, `foobar.com`, `baz`
// for integrated authentication.
session.defaultSession.allowNTLMCredentialsForDomains('*example.com, *foobar.com, *baz')

// consider all urls for integrated authentication.
session.defaultSession.allowNTLMCredentialsForDomains('*')

ses.setUserAgent(userAgent[, acceptLanguages])

  • userAgent 字串
  • acceptLanguages 字串 (選用)

覆寫此會話的 userAgentacceptLanguages

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 物件
    • minVersion 字串 (選用) - 可以是 tls1tls1.1tls1.2tls1.3。連線至遠端伺服器時允許的最小 SSL 版本。預設值為 tls1
    • maxVersion 字串 (選用) - 可以是 tls1.2tls1.3。連線至遠端伺服器時允許的最大 SSL 版本。預設值為 tls1.3
    • disabledCipherSuites Integer[] (選用) - 除了網路內建原則停用的密碼套件外,應明確禁止使用的密碼套件清單。支援的常值形式: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 字串
  • options 物件 (選用)
    • headers Record<string, string> (選用) - HTTP 請求標頭。

啟動 url 上資源的下載。API 將產生一個 DownloadItem,可以使用 will-download 事件存取。

注意: 這不會執行與頁面來源相關的任何安全性檢查,與 webContents.downloadURL 不同。

ses.createInterruptedDownload(options)

  • options 物件
    • path 字串 - 下載的絕對路徑。
    • urlChain 字串陣列 - 下載的完整 URL 鏈。
    • mimeType 字串 (選用)
    • offset 整數 - 下載的起始範圍。
    • length 整數 - 下載的總長度。
    • lastModified 字串 (選用) - Last-Modified 標頭值。
    • eTag 字串 (選用) - ETag 標頭值。
    • startTime 雙精度浮點數 (選用) - 下載開始時間,以自 UNIX Epoch 以來的秒數表示。

允許從先前的 Session 繼續 cancelledinterrupted 下載。API 將產生一個 DownloadItem,可以使用 will-download 事件存取。DownloadItem 將不會有任何與其關聯的 WebContents,且初始狀態將為 interrupted。僅當在 DownloadItem 上呼叫 resume API 時,下載才會開始。

ses.clearAuthCache()

傳回 Promise<void> - 在會話的 HTTP 驗證快取已清除時解析。

ses.setPreloads(preloads) 已停用

  • preloads 字串陣列 - 預先載入指令碼的絕對路徑陣列

新增指令碼,這些指令碼將在此會話相關聯的所有 Web 內容上執行,就在正常 preload 指令碼執行之前。

已停用: 使用新的 ses.registerPreloadScript API。

ses.getPreloads() 已停用

傳回 string[] 已註冊的預先載入指令碼路徑陣列。

已停用: 使用新的 ses.getPreloadScripts API。這只會傳回 frame 環境定義類型的預先載入指令碼路徑。

ses.registerPreloadScript(script)

註冊預先載入指令碼,該指令碼將在此會話的相關聯環境定義類型中執行。對於 frame 環境定義,這會在 WebContents 的 Web 偏好設定中定義的任何預先載入之前執行。

傳回 string - 已註冊預先載入指令碼的 ID。

ses.unregisterPreloadScript(id)

  • id 字串 - 預先載入指令碼 ID

取消註冊指令碼。

ses.getPreloadScripts()

傳回 PreloadScript[]: 已註冊的預先載入指令碼路徑陣列。

ses.setCodeCachePath(path)

  • path 字串 - 儲存來自渲染器的 v8 產生 JS 程式碼快取的絕對路徑。

設定目錄以儲存此會話產生的 JS 程式碼快取。使用者不需要在呼叫之前建立目錄,執行階段會在目錄不存在時建立,否則將使用現有目錄。如果無法建立目錄,則不會使用程式碼快取,且所有與程式碼快取相關的操作都會在執行階段內靜默失敗。依預設,目錄將位於個別使用者資料夾下的 Code Cache

請注意,依預設,程式碼快取僅針對 http(s) URL 啟用,若要為自訂協定啟用程式碼快取,在註冊協定時必須指定 codeCache: truestandard: true

ses.clearCodeCaches(options)

  • options 物件
    • urls 字串陣列 (選用) - 與需要移除產生程式碼快取的資源對應的 URL 陣列。如果清單為空,則會移除快取目錄中的所有項目。

傳回 Promise<void> - 在程式碼快取清除作業完成時解析。

ses.getSharedDictionaryUsageInfo()

傳回 Promise<SharedDictionaryUsageInfo[]> - Chromium 網路服務儲存空間中共享字典資訊項目的陣列。

共享字典用於增強透過網路傳送資料的進階壓縮,特別是 Brotli 和 ZStandard。您不需要在 Electron 中呼叫任何共享字典 API 即可使用此進階 Web 功能,但如果您這樣做,它們可以更深入地控制和檢查解壓縮期間使用的共享字典。

若要取得有關特定共享字典項目的詳細資訊,請呼叫 getSharedDictionaryInfo(options)

ses.getSharedDictionaryInfo(options)

  • options 物件
    • frameOrigin 字串 - 請求來源的框架來源。它特定於發出請求的個別框架,並由其配置、主機和連接埠定義。實際上,看起來會像 URL。
    • topFrameSite 字串 - 頂層瀏覽環境定義(包含請求的主框架或索引標籤)的網站。它不如 frameOrigin 細緻,而是著重於更廣泛的「網站」範圍。實際上,看起來會像 URL。

傳回 Promise<SharedDictionaryInfo[]> - Chromium 網路服務儲存空間中共享字典資訊項目的陣列。

若要取得有關所有目前共享字典的資訊,請呼叫 getSharedDictionaryUsageInfo()

ses.clearSharedDictionaryCache()

傳回 Promise<void> - 在字典快取已清除時解析,無論是在記憶體中還是在磁碟上。

ses.clearSharedDictionaryCacheForIsolationKey(options)

  • options 物件
    • frameOrigin 字串 - 請求來源的框架來源。它特定於發出請求的個別框架,並由其配置、主機和連接埠定義。實際上,看起來會像 URL。
    • topFrameSite 字串 - 頂層瀏覽環境定義(包含請求的主框架或索引標籤)的網站。它不如 frameOrigin 細緻,而是著重於更廣泛的「網站」範圍。實際上,看起來會像 URL。

傳回 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 上,會使用作業系統的拼字檢查器,因此我們不會下載任何字典檔案。此 API 在 macOS 上為無操作。

ses.listWordsInSpellCheckerDictionary()

傳回 Promise<string[]> - 應用程式自訂字典中所有單字的陣列。當完整字典從磁碟載入時解析。

ses.addWordToSpellCheckerDictionary(word)

  • word 字串 - 您想要新增到字典的單字

傳回 boolean - 單字是否成功寫入自訂字典。此 API 無法在非持久性(記憶體內)工作階段中使用。

注意: 在 macOS 和 Windows 10 上,此單字也會寫入作業系統的自訂字典

ses.removeWordFromSpellCheckerDictionary(word)

  • word 字串 - 您想要從字典中移除的單字

傳回 boolean - 單字是否成功從自訂字典中移除。此 API 無法在非持久性(記憶體內)工作階段中使用。

注意: 在 macOS 和 Windows 10 上,此單字也會從作業系統的自訂字典中移除

ses.loadExtension(path[, options])

  • path 字串 - 包含未封裝 Chrome 擴充功能的目錄路徑
  • options 物件 (選用)
    • allowFileAccess boolean - 是否允許擴充功能透過 file:// 協定讀取本機檔案,並將內容腳本注入到 file:// 頁面中。例如,在 file:// URL 上載入開發人員工具擴充功能時,這是必需的。預設值為 false。

傳回 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 字串 - 要移除的擴充功能 ID

卸載擴充功能。

注意: 此 API 無法在發出 app 模組的 ready 事件之前呼叫。

ses.getExtension(extensionId)

  • extensionId 字串 - 要查詢的擴充功能 ID

傳回 Extension | null - 具有給定 ID 的已載入擴充功能。

注意: 此 API 無法在發出 app 模組的 ready 事件之前呼叫。

ses.getAllExtensions()

傳回 Extension[] - 所有已載入擴充功能的列表。

注意: 此 API 無法在發出 app 模組的 ready 事件之前呼叫。

ses.getStoragePath()

傳回 string | null - 此工作階段的資料持續儲存在磁碟上的絕對檔案系統路徑。對於記憶體內工作階段,此方法傳回 null

ses.clearData([options])

  • options 物件 (選用)
    • dataTypes String[] (選用) - 要清除的資料類型。預設情況下,這將清除所有類型的資料。這可能包括此處未明確列出的資料類型。(請參閱 Chromium 的 BrowsingDataRemover 以取得完整列表。)
      • backgroundFetch - 背景擷取
      • cache - 快取(包括 cachestorageshadercache
      • cookies - Cookie
      • downloads - 下載
      • fileSystems - 檔案系統
      • indexedDB - IndexedDB
      • localStorage - 本機儲存空間
      • serviceWorkers - Service Workers
      • webSQL - WebSQL
    • origins String[] (選用) - 僅清除這些來源的資料。不能與 excludeOrigins 一起使用。
    • excludeOrigins String[] (選用) - 清除除了這些來源之外的所有來源的資料。不能與 origins 一起使用。
    • avoidClosingConnections boolean (選用) - 跳過刪除會關閉目前網路連線的 Cookie。(預設值:false
    • originMatchingMode String (選用) - 比對資料與來源的行為。
      • third-parties-included (預設) - 儲存空間在第一方環境中依來源比對,在第三方環境中依頂層網站比對。
      • origin-in-all-contexts - 儲存空間在所有環境中僅依來源比對。

傳回 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)
})