session
ブラウザーセッション、クッキー、キャッシュ、プロキシの設定などを管理します。
Process: Main
session モジュールは、新しい session オブジェクトを作成するのに使用できます。
You can also access the session of existing pages by using the session property of WebContents, or from the session module.
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ width: 800, height: 600 })
win.loadURL('https://github.com')
const ses = win.webContents.session
console.log(ses.getUserAgent())
メソッド
session モジュールには以下のメソッドがあります。
session.fromPartition(partition[, options])
partitionstring
戻り値 Session - partition 文字列からの Session のインスタンス。 同じ partition を持つ既存の session が存在する場合は、それが返されます。 それ以外の場合は、options で新しい session インスタンスが作成されます。
partition が persist: 始まりの場合、ページはアプリの全ページで利用可能な永続的なセッションを同じ partition で使用します。 persist: プレフィックスがない場合、ページは、インメモリセッションを使用します。 partition が空の場合は、アプリのデフォルトのセッションが返されます。
options で Session を作成するには、以前に partition との Session が使用されていないことを確認する必要があります。 既存の Session オブジェクトの options を変更する方法はありません。
session.fromPath(path[, options])
pathstring
戻り値 Session - path 文字列で指定された絶対パスからの Session のインスタンス。 同じ絶対パスを持つ既存の Session がある場合はそれを返します。そうでなければ、新しい Session インスタンスを options で作成します。 パスが絶対パスでない場合、この呼び出しはエラーを送出します。 さらに、空文字列が指定された場合もエラーを送出します。
Session を options で作成する場合、path を持つ Session が一度も使われていないことを確認すべきです。 既存の Session オブジェクトの options を変更する方法はありません。
プロパティ
session モジュールには以下のプロパティがあります。
session.defaultSession
アプリのデフォルトの Session オブジェクト。
クラス: Session
セッションのプロパティを取得し、設定します。
Process: Main
This class is not exported from the 'electron' module. Electron API では、他のメソッドの戻り値としてのみ利用できます。
session モジュールでは、Session オブジェクトを作成できます。
const { session } = require('electron')
const ses = session.fromPartition('persist:name')
console.log(ses.getUserAgent())
インスタンスイベント
Session のインスタンスでは、以下のイベントが利用できます。
イベント: 'will-download'
戻り値:
eventEventitemDownloadItemwebContentsWebContents
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'
戻り値:
eventEventextensionExtension
拡張機能が読み込まれた後に発生します。 これは、拡張機能が "有効な" 拡張機能のセットに追加されるたびに発生します。 これは以下のものが含まれます。
Session.loadExtensionから拡張機能が読み込まれるとき。- 拡張機能が再読み込みされるとき。
- クラッシュによって。
- 拡張機能が要求したことで (
chrome.runtime.reload())。
イベント: 'extension-unloaded'
戻り値:
eventEventextensionExtension
拡張機能が取り除かれた後に発生します。 これは Session.removeExtension が呼ばれたときに発生します。
イベント: 'extension-ready'
戻り値:
eventEventextensionExtension
拡張機能が読み込まれ、必要なブラウザの状態がすべて初期化され、拡張機能のバックグラウンドページの開始をサポートするようになった後に発生します。
イベント: 'file-system-access-restricted'
戻り値:
eventEventdetailsObjectoriginstring - ブロックされたパスへアクセスしようとしたオリジン。isDirectoryboolean - パスがディレクトリかどうか。pathstring - アクセスを試みてブロックされたパス。
callbackFunctionactionstring - 制限されたパスのアクセス試行への結果として実行するアクション。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'
戻り値:
eventEventpreconnectUrlstring - レンダラーによって事前接続に要求されている URL。allowCredentialsboolean - レンダラーが接続に資格情報を含めることを要求している場合は true です (詳細については、仕様 を参照してください)。
一般的に リソースヒント が原因で、レンダリングプロセスが URL への事前接続を要求したときに生成されます。
イベント: 'spellcheck-dictionary-initialized'
戻り値:
eventEventlanguageCodestring - 辞書ファイルの言語コード
hunspell 辞書ファイルの初期化に成功したときに発生します。 これはファイルをダウンロードした後に発生します。
イベント: 'spellcheck-dictionary-download-begin'
戻り値:
eventEventlanguageCodestring - 辞書ファイルの言語コード
hunspell 辞書ファイルのダウンロードが始まったときに発生します
イベント: 'spellcheck-dictionary-download-success'
戻り値:
eventEventlanguageCodestring - 辞書ファイルの言語コード
hunspell 辞書ファイルのダウンロードに成功したときに発生します
イベント: 'spellcheck-dictionary-download-failure'
戻り値:
eventEventlanguageCodestring - 辞書ファイルの言語コード
hunspell 辞書ファイルのダウンロードが失敗したときに発生します。 失敗の詳細は、netlog を収集してダウンロードリクエストを調べる必要があります。
イベント: 'select-hid-device'
戻り値:
eventEventdetailsObjectdeviceListHIDDevice[]frameWebFrameMain | null - The frame initiating this event. May benullif accessed after the frame has either navigated or been destroyed.
callbackFunctiondeviceIdstring | null (任意)
navigator.hid.requestDevice の呼び出し時に HID デバイスを選択する必要がある場合に発生します。 callback は選択する deviceId で呼び出してください。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') {
// ここにロジックを追加して、その HID の選択を許可するかどうかを決定します。
return true
}
return false
})
// 任意で、永続ストアから以前に永続化されたデバイスを取得します。
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) {
// 常にこのタイプのデバイスを許可します (これにより最初の `navigator.hid.requestDevice` の呼び出しをスキップできます)
return true
}
// 過去に許可されたデバイスのリストを検索します。
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'
戻り値:
eventEventdetailsObjectdeviceHIDDeviceframeWebFrameMain | null - The frame initiating this event. May benullif accessed after the frame has either navigated or been destroyed.
navigator.hid.requestDevice が呼ばれた後や、select-hid-device から呼ばれるコールバックが利用可能なる前に新しいデバイスが利用可能になると、select-hid-device が発生します。 このイベントは、UI でユーザーにデバイスの選択を求め、新しく追加されたデバイスで UI を更新するために使用することを意図しています。
イベント: 'hid-device-removed'
戻り値:
eventEventdetailsObjectdeviceHIDDeviceframeWebFrameMain | null - The frame initiating this event. May benullif accessed after the frame has either navigated or been destroyed.
navigator.hid.requestDevice が呼ばれたときや、select-hid-device のコールバックが呼ばれる前にデバイスが取り除かれた場合に、select-hid-device が発生した後に発生します。 このイベントは、UI でユーザーにデバイスの選択を求め、指定されたデバイスを取り除いて UI を更新するために使用することを意図しています。
イベント: 'hid-device-revoked'
戻り値:
eventEventdetailsObjectdeviceHIDDeviceoriginstring (任意) - デバイスが失効したオリジンです。
HIDDevice.forget() が呼ばれた後に発生します。 このイベントは、setDevicePermissionHandler が使用されたときに権限の永続ストレージの維持に利用できます。
イベント: 'select-serial-port'
戻り値:
eventEventportListSerialPort[]webContentsWebContentscallbackFunctionportIdstring
navigator.serial.requestPort の呼び出し時にシリアルポートを選択する必要がある場合に発生します。 callback は選んだ portId で呼び出されなければなりません。空の文字列を 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') {
// ここにロジックを追加して、シリアルの選択を許可すべきかどうか判断します
return true
}
return false
})
// 任意で、永続ストアから以前に永続化されたデバイスを取得します
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) {
// このタイプのデバイスを常に許可します (これにより最初の `navigator.serial.requestPort` の呼び出しを省略できます)
return true
}
// 過去に許可されたデバイスのリストを検索する
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'
戻り値:
eventEventportSerialPortwebContentsWebContents
navigator.serial.requestPort が呼ばれた後や、select-serial-port から呼ばれるコールバックが利用可能なる前に新しいシリアルポートが利用可能になると、select-serial-port が発生します。 このイベントは、UI でユーザーにポートの選択を求め、新しく追加されたポートで UI を更新するために使用することを意図しています。
イベント: 'serial-port-removed'
戻り値:
eventEventportSerialPortwebContentsWebContents
navigator.serial.requestPort が呼ばれたときや、select-serial-port のコールバックが呼ばれる前にシリアルポートが取り除かれた場合に、select-serial-port が発生した後に発生します。 このイベントは、UI でユーザーにポートの選択を求め、指定されたポートを取り除いて UI を更新するために使用することを意図しています。
イベント: 'serial-port-revoked'
戻り値:
eventEventdetailsObjectportSerialPortframeWebFrameMain | null - The frame initiating this event. May benullif accessed after the frame has either navigated or been destroyed.originstring - デバイスが失効したオリジンです。
SerialPort.forget() が呼ばれた後に発生します。 このイベントは、setDevicePermissionHandler が使用されたときに権限の永続ストレージの維持に利用できます。
// ブラウザープロセス
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}`)
})
})
// レンダラープロセス
const portConnect = async () => {
// ポートを要求します。
const port = await navigator.serial.requestPort()
// シリアルポートが開くまで待機します。
await port.open({ baudRate: 9600 })
// ...その後、シリアルポートへのアクセスを失効します。
await port.forget()
}
イベント: 'select-usb-device'
戻り値:
eventEventdetailsObjectdeviceListUSBDevice[]frameWebFrameMain | null - The frame initiating this event. May benullif accessed after the frame has either navigated or been destroyed.
callbackFunctiondeviceIdstring (任意)
navigator.usb.requestDevice の呼び出し時に USB デバイスを選択する必要がある場合に発生します。 callback は選択する deviceId で呼び出してください。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') {
// ここにロジックを追加して、その USB の選択を許可するかどうかを決定します。
return true
}
return false
})
// 任意で、永続ストアから以前に永続化されたデバイスを取得します (永続化された許可の取得には、開発者が fetchGrantedDevices を実装する必要があります)。
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) {
// 常にこのタイプのデバイスを許可します (これにより最初の `navigator.usb.requestDevice` の呼び出しをスキップできます)。
return true
}
// 過去に許可されたデバイスのリストを検索します。
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) {
// 任意で、永続化されたデバイスにこれを追加します (パーミッションの永続化には、開発者が updateGrantedDevices を実装する必要があります)。
grantedDevices.push(selectedDevice)
updateGrantedDevices(grantedDevices)
}
callback(selectedDevice?.deviceId)
})
})
イベント: 'usb-device-added'
戻り値:
eventEventdeviceUSBDevicewebContentsWebContents
navigator.usb.requestDevice が呼ばれた後や、select-usb-device から呼ばれるコールバックが利用可能なる前に新しいデバイスが利用可能になると、select-usb-device が発生します。 このイベントは、UI でユーザーにデバイスの選択を求め、新しく追加されたデバイスで UI を更新するために使用することを意図しています。
イベント: 'usb-device-removed'
戻り値:
eventEventdeviceUSBDevicewebContentsWebContents
navigator.usb.requestDevice が呼ばれたときや、select-usb-device のコールバックが呼ばれる前にデバイスが取り除かれた場合に、select-usb-device が発生した後に発生します。 このイベントは、UI でユーザーにデバイスの選択を求め、指定されたデバイスを取り除いて UI を更新するために使用することを意図しています。
イベント: 'usb-device-revoked'
戻り値:
eventEventdetailsObjectdeviceUSBDeviceoriginstring (任意) - デバイスが失効したオリジンです。
USBDevice.forget() が呼ばれた後に発生します。 このイベントは、setDevicePermissionHandler が使用されたときに権限の永続ストレージの維持に利用できます。
インスタンスメソッド
Session のインスタンスでは、以下のメソッドが利用できます。
ses.getCacheSize()
戻り値 Promise<Integer> - バイト単位の、session の現在のキャッシュサイズ。
ses.clearCache()
戻り値 Promise<void> - キャッシュクリア操作が完了すると実行されます。
セッションの HTTP キャッシュをクリアします。
ses.clearStorageData([options])
戻り値 Promise<void> - ストレージデータがクリアされると実行されます。
ses.flushStorageData()
未書き込みの DOM ストレージのデータをディスクに書き込みます。
ses.setProxy(config)
configProxyConfig
戻り値 Promise<void> - プロキシ設定処理が完了すると実行されます。
プロキシ設定を設定します。
以前のプロキシでプールされたソケットが将来のリクエストで再利用されるのを防ぐには、現在フライト中の接続を閉じるために ses.closeAllConnections が必要でしょう。
ses.resolveHost(host, [options])
hoststring - 解決するホスト名。
Returns Promise<ResolvedHost> - Resolves with the resolved IP addresses for the host.
ses.resolveProxy(url)
urlURL
戻り値 Promise<string> - url のプロキシ情報で実行されます。
ses.forceReloadProxyConfig()
戻り値 Promise<void> - プロキシサービスのすべての内部状態がリセットされたときに解決します。すでに利用可能な場合は最新のプロキシ設定が再適用されます。 プロキシモードが pac_script の場合、再び pacScript から PAC スクリプトが取得されます。
ses.setDownloadPath(path)
pathstring - ダウンロード場所。
ダウンロードの保存ディレクトリを設定します。 デフォルトでは、ダウンロードディレクトリは各アプリフォルダの下の ダウンロード (Downloads) になります。
ses.enableNetworkEmulation(options)
session の指定された構成でネットワークをエミュレートします。
const win = new BrowserWindow()
// 50kbps のスループットと 500ms の待ち時間で GPRS 接続をエミュレートします。
win.webContents.session.enableNetworkEmulation({
latency: 500,
downloadThroughput: 6400,
uploadThroughput: 6400
})
// ネットワークの切断をエミュレートします。
win.webContents.session.enableNetworkEmulation({ offline: true })
ses.preconnect(options)
指定された数のソケットをオリジンに事前接続します。
ses.closeAllConnections()
戻り値 Promise<void> - すべての接続が閉じられた時に解決されます。
[!NOTE] It will terminate / fail all requests currently in flight.
ses.fetch(input[, init])
inputstring | GlobalRequestinitRequestInit & { bypassCustomProtocolHandlers?: boolean } (任意)
Returns Promise<GlobalResponse> - see 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()
// ... 結果を使いましょう。
}
}
See also net.fetch(), a convenience method which issues requests from the default session.
See the MDN documentation for fetch() for more details.
制限事項:
net.fetch()はdata:やblob:スキームをサポートしていません。integrityオプションの値は無視されます。- 返された
Responseオブジェクトの.typeと.urlの値は不正確です。
デフォルトでは、net.fetch で行われたリクエストは カスタムプロトコル だけでなく file: に対しても許可され、webRequest ハンドラーが存在すればトリガされます。 RequestInit で非標準の bypassCustomProtocolHandlers オプションが設定されている場合、このリクエストに対してカスタムのプロトコルハンドラは呼び出されません。 これにより、干渉されるリクエストを組み込みハンドラへ転送できます。 webRequest handlers will still be triggered when bypassing custom protocols.
protocol.handle('https', (req) => {
if (req.url === 'https://my-app.com') {
return new Response('<body>my app</body>')
} else {
return net.fetch(req, { bypassCustomProtocolHandlers: true })
}
})
ses.disableNetworkEmulation()
session に対して既にアクティブなネットワークエミュレーションを無効にします。 元のネットワーク構成にリセットします。
ses.setCertificateVerifyProc(proc)
procFunction | nullrequestObjecthostnamestringcertificateCertificatevalidatedCertificateCertificateisIssuedByKnownRootboolean - Chromium がルート CA を標準ルートとして認識している場合はtrueです。 そうでない場合は、ローカルにインストールされた MITM プロキシ (企業のプロキシなど) のルートによってこの証明書が生成されている可能性があります。verificationResultがOKでない場合、信頼しないでください。verificationResultstring - 証明書が信頼されている場合はOKに、さもなくばCERT_REVOKEDのようなエラーになります。errorCodeInteger - エラーコード。
callbackFunctionverificationResultInteger - こちら の証明書エラーコードのうち一つの値を取ります。 証明書エラーコードの他に、以下の特殊コードを取ることがあります。0- 成功を示し、証明書の透明性の検証を無効にします。-2- 失敗を示します。-3- Chromium からの認証結果を使用します。
session の証明書検証プロセスを設定し、サーバー証明書の検証が要求されるたびにproc を proc(request, callback) で呼びます。 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)
handlerFunction | nullwebContentsWebContents - WebContents requesting the permission. リクエストがサブフレームからのものである場合、リクエストのオリジンを確認するためにはrequestingUrlを使用する必要があることに注意してください。permissionstring - 要求されたパーミッションのタイプ。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- サードパーティのコンテキストで読み込まれたコンテンツが、Storage Access API を用いてサードパーティ Cookie へのアクセスを要求できるようにします。top-level-storage-access- トップレベルサイトが Storage Access API を用いて、同じ関連ウェブサイトセット内の別サイトが生成した埋め込みコンテンツの代理として、サードパーティ Cookie へのアクセスを要求できるようにします。window-management-getScreenDetailsAPI を使用して画面をエミュレートするアクセスをリクエストします。unknown- 認識されない認可リクエスト.fileSystem- ファイルシステム API を用いた、読み取り、書き込み、およびファイル管理機能へのアクセスをリクエストします。
callbackFunctionpermissionGrantedboolean - 権限の許可か拒否.
detailsPermissionRequest | FilesystemPermissionRequest | MediaAccessPermissionRequest | OpenExternalPermissionRequest - 要求されている権限に関する追加情報。
session の、権限の要求に応答するために使用できるハンドラを設定します。 callback(true) を呼ぶと権限が許可され callback(false) を呼ぶと拒否されます。 ハンドラをクリアするには、setPermissionRequestHandler(null) を呼びます。 注意として、完全な認可処理にするには setPermissionCheckHandler も実装しなければなりません。 ほとんどのウェブ API は権限の確認を行い、確認が拒否されている場合は認可のリクエストを行います。
const { session } = require('electron')
session.fromPartition('some-partition').setPermissionRequestHandler((webContents, permission, callback) => {
if (webContents.getURL() === 'some-host' && permission === 'notifications') {
return callback(false) // 拒否。
}
callback(true)
})
ses.setPermissionCheckHandler(handler)
handlerFunction<boolean> | nullwebContents(WebContents | null) - WebContents checking the permission. リクエストがサブフレームからのものである場合、リクエストのオリジンを確認するためにはrequestingUrlを使用する必要があることに注意してください。 すべてのクロスオリジンサブフレームによる権限の確認はハンドラの webContents にnullが渡されますが、notificationsの確認のような、ある特定の権限の確認では常にnullが渡されます。embeddingOriginとrequestingOriginを使用して、所有しているフレームと要求しているフレームがそれぞれどのオリジンにあるかを判断する必要があります。permissionstring - 権限確認の種別。clipboard-read- クリップボードからの読み取りアクセスを要求する。clipboard-sanitized-write- クリップボードへの書き込みアクセスを要求します。geolocation- 位置情報 API 経由でのユーザーの位置情報へのアクセスです。fullscreen- 全画面 API を介して、アプリの全画面状態を制御します。hid- HID プロトコルにアクセスし、WebHID API を介して HID デバイスを操作します。idle-detection- IdleDetector API 経由でユーザーの待機状態へアクセスします。media- カメラ、マイク、スピーカーなどのメディアデバイスへアクセスします。mediaKeySystem- DRM で保護されたコンテンツへアクセスします。midi- Web MIDI API での MIDI アクセスを有効化します。midiSysex- Web MIDI API でのシステム排他メッセージを使用します。notifications- 通知 API を使用してデスクトップ通知を構成しユーザーへ表示します。openExternal- 外部アプリケーションでリンクを開きます。pointerLock- ポインターロック API を介して入力メソッドとしてマウスの動きに直接干渉します。 これらのリクエストは、常にメインフレームから送信されているように見えます。serial- Web Serial API を使用して、シリアルデバイスとの読み取りと書き込みを行います。storage-access- サードパーティのコンテキストで読み込まれたコンテンツが、Storage Access API を用いてサードパーティ Cookie へのアクセスを要求できるようにします。top-level-storage-access- トップレベルサイトが Storage Access API を用いて、同じ関連ウェブサイトセット内の別サイトが生成した埋め込みコンテンツの代理として、サードパーティ Cookie へのアクセスを要求できるようにします。usb- WebUSB API を使用して、非標準のユニバーサルシリアルバス (USB) 互換デバイスのサービスをウェブへ公開します。deprecated-sync-clipboard-readDeprecated - Request access to rundocument.execCommand("paste")fileSystem- Access to read, write, and file management capabilities using the File System API.
requestingOriginstring - 権限チェックのオリジン URLdetailsObject - このプロパティの一部は、特定の権限タイプでのみ使用できます。embeddingOriginstring (任意) - 権限の確認をしたフレームのオリジン。 権限の確認を行うクロスオリジンのサブフレームでのみ設定されます。securityOriginstring (任意) -mediaの確認でのセキュリティオリジン。mediaTypestring (optional) - The type of media access being requested, can bevideo,audioorunknown.requestingUrlstring (任意) - リクエストしているフレームが読み込んだ最後の URL. 権限の確認を行うクロスオリジンのサブフレームでは提供されません。isMainFrameboolean - リクエストしたフレームがメインフレームかどうか.filePathstring (optional) - The path of afileSystemrequest.isDirectoryboolean (optional) - Whether afileSystemrequest is a directory.fileAccessTypestring (optional) - The access type of afileSystemrequest.writableもしくはreadable。
session の、権限のチェックに応答するために使用できるハンドラを設定します。 trueを返すと権限を許可し、false を返すとそれを拒否します。 注意として、完全な認可処理にするには setPermissionRequestHandler も実装しなければなりません。 ほとんどのウェブ API は権限の確認を行い、確認が拒否されている場合は認可のリクエストを行います。 ハンドラをクリアするには、 setPermissionCheckHandler(null) を呼びます。
const { session } = require('electron')
const url = require('node:url')
session.fromPartition('some-partition').setPermissionCheckHandler((webContents, permission, requestingOrigin) => {
if (new URL(requestingOrigin).hostname === 'some-host' && permission === 'notifications') {
return true // granted
}
return false // denied
})
isMainFrame will always be false for a fileSystem request as a result of Chromium limitations.
ses.setDisplayMediaRequestHandler(handler[, opts])
handlerFunction | nullrequestObjectframeWebFrameMain | null - Frame that is requesting access to media. May benullif accessed after the frame has either navigated or been destroyed.securityOriginString - リクエストしているページのオリジンです。videoRequestedBoolean - ウェブコンテンツが映像ストリームをリクエストしていると true です。audioRequestedBoolean - ウェブコンテンツが音声ストリームをリクエストしていると true です。userGestureBoolean - リクエストがトリガされたときにユーザージェスチャが有効だったかどうかです。
callbackFunctionstreamsオブジェクトvideoObject | WebFrameMain (optional)idString - 認可されたストリームの ID です。 This will usually come from a DesktopCapturerSource object.nameString - 認可されたストリームの名前です。 This will usually come from a DesktopCapturerSource object.
audioString | WebFrameMain (optional) - If a string is specified, can beloopbackorloopbackWithMute. ループバックデバイスを指定すると、システムオーディオをキャプチャできます。これは現在 Windows でのみサポートされています。 WebFrameMain が指定されている場合はそのフレームからの音声をキャプチャします。enableLocalEchoBoolean (optional) - Ifaudiois a WebFrameMain and this is set totrue, then local playback of audio will not be muted (e.g. usingMediaRecorderto recordWebFrameMainwith this flag set totruewill allow audio to pass through to the speakers while recording). 省略値はfalseです。
optsObject (optional) macOS ExperimentaluseSystemPickerBoolean - true if the available native system picker should be used. 省略値はfalseです。 macOS Experimental
このハンドラは、navigator.mediaDevices.getDisplayMedia API を通じてウェブコンテンツがディスプレイメディアへのアクセスを要求したときに呼び出されます。 Use the desktopCapturer API to choose which stream(s) to grant access to.
useSystemPicker allows an application to use the system picker instead of providing a specific video source from getSources. This option is experimental, and currently available for MacOS 15+ only. If the system picker is available and useSystemPicker is set to true, the handler will not be invoked.
const { session, desktopCapturer } = require('electron')
session.defaultSession.setDisplayMediaRequestHandler((request, callback) => {
desktopCapturer.getSources({ types: ['screen'] }).then((sources) => {
// 最初に見つけた画面へのアクセスを認可します。
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 })
Passing a WebFrameMain object as a video or audio stream will capture the video or audio stream from that frame.
const { session } = require('electron')
session.defaultSession.setDisplayMediaRequestHandler((request, callback) => {
// タブに自身のキャプチャを許可します。
callback({ video: request.frame })
})
関数の代わりに null を渡すとハンドラはデフォルトの状態にリセットされます。
ses.setDevicePermissionHandler(handler)
handlerFunction<boolean> | nulldetailsObjectdeviceTypestring - 許可が求められているデバイスのタイプで、hid、serialまたはusbになります。originstring - デバイス権限チェックのオリジン URL。deviceHIDDevice | SerialPort | USBDevice - the device that permission is being requested for.
デバイスの権限チェックの応答に使用できるハンドラを session に設定します。 true を返すとデバイスに権限を許可し、false を返すとそれを拒否します。 ハンドラを消去するには setDevicePermissionHandler(null) と呼び出します。 このハンドラは、最初にデバイスへの許可の呼び出しを (navigator.hid.requestDevice などを介して) せずに、デバイスへのデフォルト権限を提供するために利用できます。 このハンドラが定義されていない場合、(navigator.hid.requestDevice などを介した) デバイスの選択において付与された権限をデフォルトのデバイス権限として使用します。 更に、Electron の既定の動作では付与されたデバイス権限をメモリに保持します。 より長期間の保存が必要な場合、開発者は付与されたデバイスのパーミッションを保存し (select-hid-device イベントを処理するときなど)、setDevicePermissionHandler でそのストレージから読み出しできます。
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') {
// ここにロジックを追加して、その HID の選択を許可するかどうかを決定します。
return true
} else if (permission === 'serial') {
// ここにロジックを追加して、そのシリアルポートの選択を許可するかどうかを決定します。
} else if (permission === 'usb') {
// ここにロジックを追加して、その USB デバイスの選択を許可するかどうかを決定します。
}
return false
})
// 任意で、永続ストアから以前に永続化されたデバイスを取得します。
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) {
// 常にこのタイプのデバイスを許可します (これにより最初の `navigator.hid.requestDevice` の呼び出しをスキップできます)。
return true
}
// 過去に許可されたデバイスのリストを検索します。
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) {
// 常にこのタイプのデバイスを許可します (これにより最初の `navigator.hid.requestDevice` の呼び出しをスキップできます)。
return true
}
}
return false
})
win.webContents.session.on('select-hid-device', (event, details, callback) => {
event.preventDefault()
const selectedDevice = details.deviceList.find((device) => {
return device.vendorId === 9025 && device.productId === 67
})
callback(selectedDevice?.deviceId)
})
})
ses.setUSBProtectedClassesHandler(handler)
handlerFunction<string[]> | nulldetailsObjectprotectedClassesstring[] - 保護された USB クラスの現在のリストです。 クラスの値は以下のいずれかを取ることがあります。audioaudio-videohidmass-storagesmart-cardvideowireless
Sets the handler which can be used to override which USB classes are protected. ハンドラの戻り値は、保護されている (例えばレンダラーでは利用できない) USB クラス文字列の配列です。 配列で有効な値は以下のとおりです。
audioaudio-videohidmass-storagesmart-cardvideowireless
ハンドラから空の文字列配列を返すと、すべての USB クラスが許可されます。引数に渡された配列を返すと、保護された USB クラスのデフォルトのリストが維持されます (これはハンドラーが定義されていない場合のデフォルトの動作でもあります)。 ハンドラを消去するには setUSBProtectedClassesHandler(null) と呼び出します。
const { app, BrowserWindow } = require('electron')
let win = null
app.whenReady().then(() => {
win = new BrowserWindow()
win.webContents.session.setUSBProtectedClassesHandler((details) => {
// 全てのクラスを許可するには:
// return []
// 保護クラスの現在のセットを維持するには:
// return details.protectedClasses
// 選択的にクラスを除去するには:
return details.protectedClasses.filter((usbClass) => {
// オーディオのクラスを除きます
return usbClass.indexOf('audio') === -1
})
})
})
ses.setBluetoothPairingHandler(handler) Windows Linux
handlerFunction | nulldetailsObjectdeviceIdstringpairingKindstring - リクエストしているペアリングの確認の種類です。 以下の値のいずれかです。confirmこのプロンプトはその Bluetooth デバイスをペアリングするかどうか確認するものです。confirmPinこのプロンプトは指定された PIN がデバイス上に表示された PIN と一致するかどうか確認するものです。providePinこのプロンプトはデバイスに PIN の提供を要求するものです。
frameWebFrameMain | null - The frame initiating this handler. May benullif accessed after the frame has either navigated or been destroyed.pinstring (任意) -pairingKindがconfirmPinのとき、検証する PIN の値です。
callbackFunctionresponseObjectconfirmedboolean - ダイアログがキャンセルされたならば、falseが渡されます。pairingKindがconfirmやconfirmPinであれば、この値はペアリングが承認されたことを示します。pairingKindがprovidePinの場合は、提供されているならばこの値はtrueになります。pinstring | null (任意) -pairingKindがprovidePinのとき、この値は Bluetooth デバイスに必要な PIN になります。
Bluetooth のペアリング要求に応答するハンドラを設定します。 このハンドラにより、開発者はペアリングの前に追加の検証を必要とするデバイスを扱えます。 ハンドラが定義されていない場合、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
// レンダラーに IPC メッセージを送信し、ユーザーにペアリングの確認を促します。
// 注意として、このメッセージの処理してユーザーに表示するには、
// レンダラーにもロジックが必要です。
mainWindow.webContents.send('bluetooth-pairing-request', details)
})
// Bluetooth ペアリングのレスポンスを取得するために、レンダラーからの IPC メッセージをリッスンします。
mainWindow.webContents.ipc.on('bluetooth-pairing-response', (event, response) => {
bluetoothPinCallback(response)
})
}
app.whenReady().then(() => {
createWindow()
})
ses.clearHostResolverCache()
戻り値 Promise<void> - 操作が完了すると実行されます。
ホスト解決のキャッシュをクリアします。
ses.allowNTLMCredentialsForDomains(domains)
domainsstring - 統合認証が有効であるサーバーのカンマ区切りのリスト。
HTTP NTLM またはネゴシエート認証の資格情報を常に送信するかどうかを動的に設定します。
const { session } = require('electron')
// 統合認証において、 `example.com`、`foobar.com`、`baz` で終わる
// URL を考えます。
session.defaultSession.allowNTLMCredentialsForDomains('*example.com, *foobar.com, *baz')
// 統合認証に、すべての URL を考えます。
session.defaultSession.allowNTLMCredentialsForDomains('*')
ses.setUserAgent(userAgent[, acceptLanguages])
userAgentstringacceptLanguagesstring (任意)
このセッションの 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)
configObjectminVersionstring (任意) -tls1、tls1.1、tls1.2、tls1.3のいずれかにできます。 これはリモートサーバーに接続する際に許可する最小の SSL バージョンです。 省略値はtls1です。maxVersionstring (任意) -tls1.2かtls1.3にできます。 これはリモートサーバーに接続する際に許可する最大の SSL バージョンです。 省略値はtls1.3です。disabledCipherSuitesInteger[] (任意) - ネット組み込みポリシーで無効化されたものに加えて、使用を禁止すべき暗号スートを明示したリスト。 0xAABB のようなリテラルの形式をサポートしています。ここで AA はcipher_suite[0]であり、BB はcipher_suite[1]です。これは RFC 2246 のセクション 7.4.1.2 で定義されています。 識別不可かつパース可能な暗号スートの形式であっても、エラーは返しません。 例: TLS_RSA_WITH_RC4_128_MD5 を無効にするには、0x0004 を指定し、TLS_ECDSA_WITH_RC4_128_SHA を無効にするには 0xC002 を指定します。 注意として、TLSv1.3 の暗号化方式はこの仕組みで無効にできません。
セッションの SSL 構成を設定します。 それ以降のネットワークリクエストではすべて新しい構成を使用します。 既存のネットワーク接続 (WebSocket 接続など) は終了しませんが、プール内の古いソケットは新しい接続に再利用されません。
ses.getBlobData(identifier)
identifierstring - 有効な UUID。
Returns Promise<Buffer> - resolves with blob data.
ses.downloadURL(url[, options])
urlstring
url にあるリソースのダウンロードを初期化します。 The API will generate a DownloadItem that can be accessed with the will-download event.
[!NOTE] This does not perform any security checks that relate to a page's origin, unlike
webContents.downloadURL.
ses.createInterruptedDownload(options)
以前の Session からの、cancelled または interrupted なダウンロードの再開を許可します。 The API will generate a DownloadItem that can be accessed with the will-download event. The DownloadItem will not have any WebContents associated with it and the initial state will be interrupted. The download will start only when the resume API is called on the DownloadItem.
ses.clearAuthCache()
戻り値 Promise<void> - session の HTTP 認証キャッシュがクリアされると実行されます。
ses.setPreloads(preloads) 非推奨
preloadsstring[] - プリロードスクリプトへの絶対パスの配列
通常の preload スクリプトが実行される直前に、このセッションに関連するすべてのウェブコンテンツで実行されるスクリプトを追加します。
非推奨: 新しい ses.registerPreloadScript API を使用してください。
ses.getPreloads() 非推奨
戻り値 string[] - 登録されているプリロードスクリプトへのパスの配列。
非推奨: 新しい ses.getPreloadScripts API を使用してください。 This will only return preload script paths for frame context types.
ses.registerPreloadScript(script)
scriptPreloadScriptRegistration - Preload script
Registers preload script that will be executed in its associated context type in this session. For frame contexts, this will run prior to any preload defined in the web preferences of a WebContents.
Returns string - The ID of the registered preload script.
ses.unregisterPreloadScript(id)
idstring - Preload script ID
Unregisters script.
ses.getPreloadScripts()
Returns PreloadScript[]: An array of paths to preload scripts that have been registered.
ses.setCodeCachePath(path)
pathString - レンダラーが v8 で生成された JS のコードキャッシュを格納する絶対パス。
Sets the directory to store the generated JS code cache for this session. このディレクトリは、呼び出し以前にユーザーが作成しておく必要はありません。ランタイムは、存在しない場合には作成し、そうでない場合は既存のディレクトリを使用します。 ディレクトリを作成できない場合、コードキャッシュは使用されず、コードキャッシュに関連するすべての操作はランタイム内でエラーを出さずに失敗します。 デフォルトでは、それぞれのユーザーデータフォルダー配下の Code Cache というディレクトリです。
注意として、コードキャッシュはデフォルトで http(s) URL に対してのみ有効になっています。カスタムプロトコルに対してコードキャッシュを有効化するには、プロトコルの登録時に codeCache: true と standard: true を指定する必要があります。
ses.clearCodeCaches(options)
戻り値 Promise<void> - コードキャッシュの消去操作が完了すると解決されます。
ses.getSharedDictionaryUsageInfo()
Returns Promise<SharedDictionaryUsageInfo[]> - an array of shared dictionary information entries in Chromium's networking service's storage.
Shared dictionaries are used to power advanced compression of data sent over the wire, specifically with Brotli and ZStandard. You don't need to call any of the shared dictionary APIs in Electron to make use of this advanced web feature, but if you do, they allow deeper control and inspection of the shared dictionaries used during decompression.
To get detailed information about a specific shared dictionary entry, call getSharedDictionaryInfo(options).
ses.getSharedDictionaryInfo(options)
Returns Promise<SharedDictionaryInfo[]> - an array of shared dictionary information entries in Chromium's networking service's storage.
To get information about all present shared dictionaries, call getSharedDictionaryUsageInfo().
ses.clearSharedDictionaryCache()
Returns Promise<void> - resolves when the dictionary cache has been cleared, both in memory and on disk.
ses.clearSharedDictionaryCacheForIsolationKey(options)
Returns Promise<void> - resolves when the dictionary cache has been cleared for the specified isolation key, both in memory and on disk.
ses.setSpellCheckerEnabled(enable)
enableboolean
組み込みスペルチェッカーを有効にするかどうかを設定します。
ses.isSpellCheckerEnabled()
戻り値 boolean - 組み込みスペルチェッカーが有効化されているかどうか。
ses.setSpellCheckerLanguages(languages)
languagesstring[] - スペルチェッカーを有効にする言語コードの配列。
組み込みスペルチェッカーは、ユーザーが入力している言語を自動的に検出しません。 スペルチェッカーが単語を正しくチェックするには、言語コードの配列でこの API を呼び出す必要があります。 ses.availableSpellCheckerLanguages プロパティで、サポートしている言語コードのリストを取得できます。
[!NOTE] On macOS, the OS spellchecker is used and will detect your language automatically. この API は、macOS では何もしません。
ses.getSpellCheckerLanguages()
戻り値 string[] - スペルチェッカーが有効になっている言語コードの配列。 このリストが空の場合、スペルチェッカーは en-US の使用へフォールバックします。 この設定が空のリストである場合、Electron は起動時に既定で現在の OS ロケールをこの設定に追加しようとします。 この設定は再起動後も持続します。
[!NOTE] On macOS, the OS spellchecker is used and has its own list of languages. macOS の場合、この API は OS の設定言語を返します。
ses.setSpellCheckerDictionaryDownloadURL(url)
urlstring - Electron が hunspell 辞書をダウンロードする基底 URL。
デフォルトでは、Electron は Chromium CDN から hunspell 辞書をダウンロードします。 この動作をオーバーライドする場合は、この API を使用して、独自ホスト版の hunspell 辞書を辞書ダウンローダーが指すようにすることができます。 ホストに必要なファイルが入っている、各リリースの hunspell_dictionaries.zip ファイルをこちらで公開しています。
The file server must be case insensitive. できない場合、各ファイルを 2 回アップロードする必要があります。1 回目はその ZIP ファイルの大文字小文字のままで、2 回目はファイル名をすべて小文字にしてアップロードしてください。
hunspell_dictionaries.zip が https://example.com/dictionaries/language-code.bdic に存在して利用できる場合、ses.setSpellCheckerDictionaryDownloadURL('https://example.com/dictionaries/') を呼び出すことになります。 末尾のスラッシュに注意してください。 辞書への URL は、${url}${filename} の形式になります。
[!NOTE] On macOS, the OS spellchecker is used and therefore we do not download any dictionary files. この API は、macOS では何もしません。
ses.listWordsInSpellCheckerDictionary()
戻り値 Promise<string[]> - アプリのカスタム辞書の全単語の配列。 ディスクから完全な辞書が読み込まれたときに解決されます。
ses.addWordToSpellCheckerDictionary(word)
wordstring - 辞書に追加したい単語
戻り値 boolean - 単語がカスタム辞書に正常に書き込まれたかどうか。 この API は、持続的でない (一時的な) セッションでは動作しません。
[!NOTE] On macOS and Windows, this word will be written to the OS custom dictionary as well.
ses.removeWordFromSpellCheckerDictionary(word)
wordstring - 辞書から削除したい単語
戻り値 boolean - 単語がカスタム辞書から正常に削除されたかどうか。 この API は、持続的でない (一時的な) セッションでは動作しません。
[!NOTE] On macOS and Windows, this word will be removed from the OS custom dictionary as well.
ses.loadExtension(path[, options]) 非推奨
pathstring - 解凍されていない Chrome 拡張機能を含んだディレクトリへのパス
Returns Promise<Extension> - resolves when the extension is loaded.
このメソッドは、拡張機能を読み込めなかった場合に例外を発生させます。 拡張機能のインストール時に警告が発生した場合 (Electron が未サポートの API を拡張機能が要求した場合など) は、コンソールにログが記録されます。
注意として、Electron は Chrome 拡張機能の API のすべてをサポートしていません。 See Supported Extensions APIs for more details on what is supported.
注意として、以前のバージョンの 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 は、file:// の URL でデベロッパーツール拡張モジュールを読み込むために必要です。
{ allowFileAccess: true }
)
// 注意として、React デベロッパー ツール拡張機能を使用するにはそのコピーを
// ダウンロードして解凍する必要があります。
})
この API は、パッケージした (.crx) 拡張機能の読み込みをサポートしていません。
[!NOTE] This API cannot be called before the
readyevent of theappmodule is emitted.
[!NOTE] Loading extensions into in-memory (non-persistent) sessions is not supported and will throw an error.
非推奨: 新しい ses.extensions.loadExtension API を使用してください。
ses.removeExtension(extensionId) 非推奨
extensionIdstring - 削除する拡張機能の ID
拡張機能を取り除きます。
[!NOTE] This API cannot be called before the
readyevent of theappmodule is emitted.
非推奨: 新しい ses.extensions.removeExtension API を使用してください。
ses.getExtension(extensionId) 非推奨
extensionIdstring - 取得する拡張機能の ID
Returns Extension | null - 指定した ID を持つロード済みの拡張機能。
[!NOTE] This API cannot be called before the
readyevent of theappmodule is emitted.
非推奨: 新しい ses.extensions.getExtension API を使用してください。
ses.getAllExtensions() 非推奨
戻り値 Extension[] - 読み込まれた拡張機能のリスト。
[!NOTE] This API cannot be called before the
readyevent of theappmodule is emitted.
非推奨: 新しい ses.extensions.getAllExtensions API を使用してください。
ses.getStoragePath()
戻り値 string | null - このセッションのデータが保存されている、ディスク上のファイルシステムの絶対パスです。 インメモリセッションの場合、これは null を返します。
ses.clearData([options])
戻り値 Promise<void> - 全てのデータがクリアされたときに解決します。
さまざまな種類のデータを消去します。
このメソッドは、clearStorageData メソッドよりも徹底的に多くの種類のデータをクリアします。
[!NOTE] Cookies are stored at a broader scope than origins. 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 が消去されます。
[!NOTE] Clearing cache data will also clear the shared dictionary cache. This means that any dictionaries used for compression may be reloaded after clearing the cache. If you wish to clear the shared dictionary cache but leave other cached data intact, you may want to use the
clearSharedDictionaryCachemethod.
詳細については、Chromium の BrowsingDataRemover インターフェイス をご参照ください。
インスタンスプロパティ
Session のインスタンスには以下のプロパティがあります。
ses.availableSpellCheckerLanguages 読み出し専用
この string[] 配列は利用可能な既知のすべてのスペルチェッカー言語で構成されます。 この配列にない言語コードを setSpellCheckerLanguages API に提供すると、エラーが発生します。
ses.spellCheckerEnabled
boolean 型で、組み込みスペルチェッカーが有効かどうかを示します。
ses.storagePath 読み出し専用
string | null 型で、このセッションのデータが保存されているディスクのファイルシステムの絶対パスを示します。 インメモリセッションの場合、これは null を返します。
ses.cookies 読み出し専用
A Cookies object for this session.
ses.extensions 読み出し専用
A Extensions object for this session.
ses.serviceWorkers 読み出し専用
A ServiceWorkers object for this session.
ses.webRequest 読み出し専用
A WebRequest object for this session.
ses.protocol 読み出し専用
A Protocol object for this session.
const { app, session } = require('electron')
const path = require('node:path')
app.whenReady().then(() => {
const protocol = session.fromPartition('some-partition').protocol
if (!protocol.registerFileProtocol('atom', (request, callback) => {
const url = request.url.substr(7)
callback({ path: path.normalize(path.join(__dirname, url)) })
})) {
console.error('Failed to register protocol')
}
})
ses.netLog 読み出し専用
A NetLog object for this session.
const { app, session } = require('electron')
app.whenReady().then(async () => {
const netLog = session.fromPartition('some-partition').netLog
netLog.startLogging('/path/to/net-log')
// ネットワークイベントの後
const path = await netLog.stopLogging()
console.log('Net-logs written to', path)
})