session
ブラウザセッション、クッキー、キャッシュ、プロキシ設定などを管理します。
プロセス: メイン
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
がある場合は、それが返されます。それ以外の場合は、新しいSession
インスタンスがoptions
付きで作成されます。
partition
が persist:
で始まる場合、ページはアプリ内の同じ partition
を持つすべてのページで利用可能な永続セッションを使用します。 persist:
プレフィックスがない場合、ページはインメモリセッションを使用します。 partition
が空の場合、アプリのデフォルトセッションが返されます。
options
を使用して Session
を作成するには、partition
を持つ Session
がこれまで使用されたことがないことを確認する必要があります。既存の Session
オブジェクトの options
を変更する方法はありません。
session.fromPath(path[, options])
path
文字列
Session
を返します - path
文字列で指定された絶対パスから取得したセッションインスタンス。同じ絶対パスを持つ既存のSession
がある場合は、それが返されます。それ以外の場合は、新しいSession
インスタンスがoptions
付きで作成されます。パスが絶対パスでない場合、呼び出しはエラーをスローします。さらに、空の文字列が提供された場合にもエラーがスローされます。
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
はプロセスの次のティックから利用できなくなります。
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
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
callback
関数deviceId
string | null (オプション)
navigator.hid.requestDevice
の呼び出しが行われたときにHIDデバイスを選択する必要がある場合に発生します。選択するdeviceId
を使用してcallback
を呼び出す必要があります。callback
に引数を渡さないと、リクエストがキャンセルされます。さらに、navigator.hid
のパーミッションは、ses.setPermissionCheckHandler(handler)
および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
イベントdetails
オブジェクトdevice
HIDDeviceframe
WebFrameMain
navigator.hid.requestDevice
が呼び出され、select-hid-device
からのコールバックが呼び出される前に新しいデバイスが利用可能になった場合、select-hid-device
が発生した後に発生します。このイベントは、ユーザーにデバイスを選択するように要求するUIを使用している場合に、新しく追加されたデバイスでUIを更新できるようにするために使用することを目的としています。
イベント: 'hid-device-removed'
返却値
event
イベントdetails
オブジェクトdevice
HIDDeviceframe
WebFrameMain
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
に空の文字列を渡すとリクエストがキャンセルされます。さらに、navigator.serial
のパーミッションは、serial
パーミッションとともに ses.setPermissionCheckHandler(handler) を使用して管理できます。
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
WebFrameMainorigin
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
callback
関数deviceId
string (オプション)
navigator.usb.requestDevice
が呼び出されたときにUSBデバイスを選択する必要がある場合に発生します。選択する deviceId
を指定して callback
を呼び出す必要があります。 callback
に引数を渡さないとリクエストがキャンセルされます。さらに、navigator.usb
のパーミッションは、ses.setPermissionCheckHandler(handler)
および 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
イベント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>
を返します - プロキシ設定プロセスが完了すると解決されます。
プロキシ設定を設定します。
現在進行中の接続を閉じ、以前のプロキシを使用しているプールされたソケットが今後のリクエストで再利用されるのを防ぐために、ses.closeAllConnections
が必要になる場合があります。
ses.resolveHost(host, [options])
host
string - 解決するホスト名。
Promise<ResolvedHost> を返します - host
の解決済みIPアドレスで解決されます。
ses.resolveProxy(url)
url
URL
Promise<string>
を返します - url
のプロキシ情報で解決されます。
ses.forceReloadProxyConfig()
Promise<void>
を返します - プロキシサービスのすべての内部状態がリセットされ、利用可能な場合は最新のプロキシ構成が再度適用されると解決されます。プロキシモードが pac_script
の場合、pacスクリプトは pacScript
から再度フェッチされます。
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)
指定された数のソケットをオリジンにプリコネクトします。
ses.closeAllConnections()
Promise<void>
を返します - すべての接続が閉じられたときに解決されます。
注意: 現在進行中のすべてリクエストを終了/失敗させます。
ses.fetch(input[, init])
input
string | 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()
も参照してください。これはデフォルトセッションからリクエストを発行する便利なメソッドです。
詳細については、fetch()
に関するMDNドキュメントを参照してください。
制限事項
net.fetch()
はdata:
またはblob:
スキームをサポートしていません。integrity
オプションの値は無視されます。- 返される
Response
オブジェクトの.type
および.url
の値は正しくありません。
デフォルトでは、net.fetch
で行われたリクエストは、カスタムプロトコルだけでなく、file:
にも行うことができ、存在する場合は webRequest ハンドラをトリガーします。非標準の bypassCustomProtocolHandlers
オプションがRequestInitで設定されている場合、カスタムプロトコルハンドラはこのリクエストに対して呼び出されません。これにより、インターセプトされたリクエストを組み込みのハンドラに転送できます。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
Function | nullrequest
Objecthostname
stringcertificate
CertificatevalidatedCertificate
CertificateisIssuedByKnownRoot
boolean - ChromiumがルートCAを標準ルートとして認識している場合はtrue
です。そうでない場合は、ローカルにインストールされているルートを持つMITMプロキシ(たとえば、企業プロキシ)によってこの証明書が生成された可能性があります。verificationResult
がOK
でない場合、これは信頼すべきではありません。verificationResult
string - 証明書が信頼されている場合は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
Function | nullwebContents
WebContents - 権限を要求しているWebContents。リクエストがサブフレームからのものである場合は、リクエストのオリジンを確認するためにrequestingUrl
を使用する必要があることに注意してください。permission
string - 要求された権限の種類。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 権限ポリシーを介してオーディオ出力デバイスを列挙および選択するように要求します。storage-access
- Storage Access APIを使用して、サードパーティコンテキストでロードされたコンテンツがサードパーティCookieへのアクセスを要求できるようにします。top-level-storage-access
- Storage Access APIを使用して、トップレベルサイトが、関連する同じウェブサイトセット内の別のサイトから発信された埋め込みコンテンツに代わってサードパーティCookieアクセスを要求できるようにします。window-management
-getScreenDetails
APIを使用して画面を列挙するためのアクセスを要求します。unknown
- 認識されない権限リクエスト。fileSystem
- File System APIを使用して、読み取り、書き込み、およびファイル管理機能へのアクセスを要求します。
callback
関数permissionGranted
boolean - 権限を許可または拒否します。
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
string - 権限チェックの種類。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
- Storage Access APIを使用して、トップレベルサイトが、関連する同じウェブサイトセット内の別のサイトから発信された埋め込みコンテンツに代わってサードパーティCookieアクセスを要求できるようにします。usb
- WebUSB API を使用して、非標準の Universal Serial Bus (USB) 互換デバイスサービスを Web に公開します。
requestingOrigin
string - 許可チェックのオリジン URLdetails
Object - 一部のプロパティは、特定の許可タイプでのみ利用可能です。embeddingOrigin
string (オプション) - 許可チェックを行ったフレームを埋め込んでいるフレームのオリジン。クロスオリジンサブフレームが許可チェックを行う場合にのみ設定されます。securityOrigin
string (オプション) -media
チェックのセキュリティオリジン。mediaType
string (オプション) - リクエストされているメディアアクセスのタイプ。video
、audio
、またはunknown
が可能です。requestingUrl
string (オプション) - リクエストを行ったフレームが最後にロードした 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
Function | nullrequest
Objectframe
WebFrameMain - メディアへのアクセスをリクエストしているフレーム。securityOrigin
String - リクエストを行っているページのオリジン。videoRequested
Boolean - Web コンテンツがビデオストリームをリクエストした場合に true。audioRequested
Boolean - Web コンテンツがオーディオストリームをリクエストした場合に 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
を使用してこのフラグがtrue
に設定されているWebFrameMain
を録音すると、録音中にオーディオがスピーカーに伝わるようになります)。デフォルトはfalse
です。
opts
Object (オプション) macOS 実験的useSystemPicker
Boolean - 利用可能なネイティブシステムピッカーを使用する場合は true。デフォルトはfalse
です。 macOS 実験的
このハンドラーは、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> | 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
Function | nulldetails
オブジェクトdeviceId
stringpairingKind
string - リクエストされているペアリングプロンプトのタイプ。次のいずれかの値です。confirm
このプロンプトは、Bluetooth デバイスをペアリングする必要があるという確認を要求しています。confirmPin
このプロンプトは、提供された PIN がデバイスに表示される PIN と一致するという確認を要求しています。providePin
このプロンプトは、デバイスに PIN を提供することを要求しています。
frame
WebFrameMainpin
string (オプション) -pairingKind
がconfirmPin
の場合に検証する PIN 値。
callback
関数response
Objectconfirmed
boolean - ダイアログがキャンセルされた場合はfalse
を渡す必要があります。pairingKind
がconfirm
またはconfirmPin
の場合、この値はペアリングが確認されたかどうかを示す必要があります。pairingKind
がprovidePin
の場合、値が提供された場合は値はtrue
である必要があります。pin
string | null (オプション) -pairingKind
がprovidePin
の場合、この値は Bluetooth デバイスに必要な PIN である必要があります。
Bluetooth ペアリングリクエストに対応するハンドラーを設定します。このハンドラーを使用すると、開発者はペアリング前に追加の検証が必要なデバイスを処理できます。ハンドラーが定義されていない場合、追加の検証が必要な Linux または Windows でのペアリングは自動的にキャンセルされます。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
string (オプション) -tls1.2
またはtls1.3
を指定できます。リモートサーバーに接続する際に許可する最大の SSL バージョンです。デフォルトはtls1.3
です。disabledCipherSuites
Integer[] (オプション) - ネットワークの組み込みポリシーによって無効にされているものに加えて、明示的に使用を禁止する必要がある暗号スイートのリストです。サポートされるリテラル形式は、RFC 2246 セクション 7.4.1.2 で定義されているように、0xAABB です。ここで AA はcipher_suite[0]
で、BB はcipher_suite[1]
です。この形式で認識できないが解析可能な暗号スイートはエラーを返しません。例:TLS_RSA_WITH_RC4_128_MD5 を無効にするには 0x0004 を指定し、TLS_ECDH_ECDSA_WITH_RC4_128_SHA を無効にするには 0xC002 を指定します。TLSv1.3 の暗号は、このメカニズムを使用して無効にすることはできませんので注意してください。
セッションの SSL 設定を設定します。以降のすべてのネットワークリクエストは、新しい設定を使用します。既存のネットワーク接続(WebSocket 接続など)は終了しませんが、プール内の古いソケットは新しい接続には再利用されません。
ses.getBlobData(identifier)
identifier
string - 有効な UUID。
Promise<Buffer>
を返します - blob データで解決します。
ses.downloadURL(url[, options])
url
string
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
string[] - プリロードスクリプトへの絶対パスの配列
通常の preload
スクリプトが実行される直前に、このセッションに関連付けられているすべての Web コンテンツで実行されるスクリプトを追加します。
ses.getPreloads()
string[]
を返します - 登録されているプリロードスクリプトへのパスの配列。
ses.setCodeCachePath(path)
path
String - レンダラーから生成された v8 JS コードキャッシュを格納する絶対パス。
このセッション用に生成された JS コードキャッシュを格納するディレクトリを設定します。このディレクトリは、この呼び出しの前にユーザーが作成する必要はなく、ランタイムは存在しない場合は作成し、それ以外の場合は既存のディレクトリを使用します。ディレクトリを作成できない場合、コードキャッシュは使用されず、コードキャッシュに関連するすべての操作はランタイム内でサイレントに失敗します。デフォルトでは、ディレクトリはそれぞれのユーザーデータフォルダーの下にある Code Cache
になります。
デフォルトでは、コードキャッシュは http(s) URL に対してのみ有効になっていることに注意してください。カスタムプロトコルのコードキャッシュを有効にするには、プロトコルを登録するときに codeCache: true
と standard: true
を指定する必要があります。
ses.clearCodeCaches(options)
Promise<void>
を返します - コードキャッシュのクリア操作が完了すると解決します。
ses.setSpellCheckerEnabled(enable)
enable
boolean
組み込みのスペルチェッカーを有効にするかどうかを設定します。
ses.isSpellCheckerEnabled()
boolean
を返します - 組み込みのスペルチェッカーが有効かどうか。
ses.setSpellCheckerLanguages(languages)
languages
string[] - スペルチェッカーを有効にする言語コードの配列。
組み込みのスペルチェッカーは、ユーザーが入力している言語を自動的に検出しません。スペルチェッカーで単語を正しくチェックするには、この API を言語コードの配列とともに呼び出す必要があります。サポートされている言語コードのリストは、ses.availableSpellCheckerLanguages
プロパティで取得できます。
注: macOS では、OS スペルチェッカーが使用され、言語が自動的に検出されます。この API は macOS では何もしません。
ses.getSpellCheckerLanguages()
string[]
を返します - スペルチェッカーが有効になっている言語コードの配列。このリストが空の場合、スペルチェッカーは en-US
を使用するようにフォールバックします。起動時にこの設定が空のリストの場合、Electron はこの設定に現在の OS ロケールを設定しようとします。この設定は再起動しても保持されます。
注: macOS では、OS スペルチェッカーが使用され、独自の言語リストがあります。macOS では、この API は OS によって構成された言語を返します。
ses.setSpellCheckerDictionaryDownloadURL(url)
url
string - Electron が hunspell 辞書をダウンロードするためのベース URL。
デフォルトでは、Electron は Chromium CDN から hunspell 辞書をダウンロードします。この動作をオーバーライドする場合は、この API を使用して、hunspell 辞書の独自のホストバージョンを指すように辞書ダウンローダーを指定できます。ここでは、ホストする必要があるファイルを含む hunspell_dictionaries.zip
ファイルを各リリースで公開しています。
ファイルサーバーは、大文字と小文字を区別しない必要があります。これを行うことができない場合は、ZIP ファイルにあるケースで 1 回、ファイル名をすべて小文字にした名前で 1 回と、各ファイルを 2 回アップロードする必要があります。
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 では、この単語は OS カスタム辞書にも書き込まれます。
ses.removeWordFromSpellCheckerDictionary(word)
word
string - 辞書から削除する単語
boolean
を返します - 単語がカスタム辞書から正常に削除されたかどうか。この API は、非永続(インメモリ)セッションでは機能しません。
注: macOS および Windows 10 では、この単語は OS カスタム辞書からも削除されます。
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
メソッドよりも徹底的です。
注: クッキーはオリジンよりも広いスコープで保存されます。クッキーを削除し、origins
(またはexcludeOrigins
)でフィルタリングする場合、クッキーは登録可能ドメインレベルで削除されます。たとえば、オリジンhttps://really.specific.origin.example.com/
のクッキーをクリアすると、example.com
のすべてのクッキーがクリアされます。オリジンhttps://my.website.example.co.uk/
のクッキーをクリアすると、example.co.uk
のすべてのクッキーがクリアされます。
詳細については、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)
})