session
ブラウザーセッション、クッキー、キャッシュ、プロキシの設定などを管理します。
プロセス: Main
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
string
戻り値 Session
- partition
文字列からの Session のインスタンス。 同じ partition
を持つ既存の session
が存在する場合は、それが返されます。 それ以外の場合は、options
で新しい session
インスタンスが作成されます。
partition
が persist:
始まりの場合、ページはアプリの全ページで利用可能な永続的なセッションを同じ partition
で使用します。 persist:
プレフィックスがない場合、ページは、インメモリセッションを使用します。 partition
が空の場合は、アプリのデフォルトのセッションが返されます。
options
で Session
を作成するには、以前に partition
との Session
が使用されていないことを確認する必要があります。 既存の Session
オブジェクトの options
を変更する方法はありません。
session.fromPath(path[, options])
path
string
戻り値 Session
- path
文字列で指定された絶対パスからの Session のインスタンス。 同じ絶対パスを持つ既存の Session
がある 場合はそれを返します。そうでなければ、新しい Session
インスタンスを options
で作成します。 パスが絶対パスでない場合、この呼び出しはエラーを送出します。 さらに、空文字列が指定された場合もエラーを送出します。
Session
を options
で作成する場合、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
Eventitem
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
Eventextension
Extension
拡張機能が読み込まれた後に発生します。 これは、拡張機能が "有効な" 拡張機能のセットに追加されるたびに発生します。 これは以下のものが含まれます。
Session.loadExtension
から拡張機能が読み込まれるとき。- 拡張機能が再読み込みされるとき。
- クラッシュによって。
- 拡張機能が要求したことで (
chrome.runtime.reload()
)。
イベント: 'extension-unloaded'
戻り値:
event
Eventextension
Extension
拡張機能が取り除かれた後に発生します。 これは Session.removeExtension
が呼ばれたときに発生します。
イベント: 'extension-ready'
戻り値:
event
Eventextension
Extension
拡張機能が読み込まれ、必要なブラウザの状態がすべて初期化され、拡張機能のバックグラウンドページの開始をサポートするようになった後に発生します。
Event: 'file-system-access-restricted'
戻り値:
event
Eventdetails
Objectorigin
string - The origin that initiated access to the blocked path.isDirectory
boolean - Whether or not the path is a directory.path
string - The blocked path attempting to be accessed.
callback
Functionaction
string - The action to take as a result of the restricted path access attempt.allow
- This will allowpath
to be accessed despite restricted status.deny
- This will block the access request and trigger anAbortError
.tryAgain
- This will open a new file picker and allow the user to choose another path.
const { app, dialog, BrowserWindow, session } = require('electron')
async function createWindow () {
const mainWindow = new BrowserWindow()
await mainWindow.loadURL('https://buzzfeed.com')
session.defaultSession.on('file-system-access-restricted', async (e, details, callback) => {
const { origin, path } = details
const { response } = await dialog.showMessageBox({
message: `Are you sure you want ${origin} to open restricted path ${path}?`,
title: 'File System Access Restricted',
buttons: ['Choose a different folder', 'Allow', 'Cancel'],
cancelId: 2
})
if (response === 0) {
callback('tryAgain')
} else if (response === 1) {
callback('allow')
} else {
callback('deny')
}
})
mainWindow.webContents.executeJavaScript(`
window.showDirectoryPicker({
id: 'electron-demo',
mode: 'readwrite',
startIn: 'downloads',
}).catch(e => {
console.log(e)
})`, true
)
}
app.whenReady().then(() => {
createWindow()
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
イベント: 'preconnect'
戻り値:
event
EventpreconnectUrl
string - レンダラーによって事前接続に要求されている URL。allowCredentials
boolean - レンダラーが接続に資格情報を含めることを要求している場合は true です (詳細については、仕様 を参照してください)。
一般的に リソースヒン ト が原因で、レンダリングプロセスが URL への事前接続を要求したときに生成されます。
イベント: 'spellcheck-dictionary-initialized'
戻り値:
event
EventlanguageCode
string - 辞書ファイルの言語コード
hunspell 辞書ファイルの初期化に成功したときに発生します。 これはファイルをダウンロードした後に発生します。
イベント: 'spellcheck-dictionary-download-begin'
戻り値:
event
EventlanguageCode
string - 辞書ファイルの言語コード
hunspell 辞書ファイルのダウンロードが始まったときに発生します
イベント: 'spellcheck-dictionary-download-success'
戻り値:
event
EventlanguageCode
string - 辞書ファイルの言語コード
hunspell 辞書ファイルのダウンロードに成功したときに発生します
イベント: 'spellcheck-dictionary-download-failure'
戻り値:
event
EventlanguageCode
string - 辞書ファイルの言語コード
hunspell 辞書ファイルのダウンロードが失敗したときに発生します。 失敗の詳細は、netlog を収集してダウンロードリクエストを調べる必要があります。
イベント: 'select-hid-device'
戻り値:
event
Eventdetails
ObjectdeviceList
HIDDevice[]frame
WebFrameMain
callback
FunctiondeviceId
string | 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'
戻り値:
event
Eventdetails
Objectdevice
HIDDeviceframe
WebFrameMain
navigator.hid.requestDevice
が呼ばれた後や、select-hid-device
から呼ばれるコールバックが利用可能なる前に新しいデバイスが利用可能になると、select-hid-device
が発生します。 このイベントは、UI でユーザーにデバイスの選択を求め、新しく追加されたデバイスで UI を更新するために使用することを意図しています。
イベント: 'hid-device-removed'
戻り値:
event
Eventdetails
Objectdevice
HIDDeviceframe
WebFrameMain
navigator.hid.requestDevice
が呼ばれたときや、select-hid-device
のコールバックが呼ばれる前にデバイスが取り除かれた場合に、select-hid-device
が発生した後に発生します。 このイベントは、UI でユーザーにデバイスの選択を求め、指定されたデバイスを取り除いて UI を更新するために使用することを意図しています。
イベント: 'hid-device-revoked'
戻り値:
event
Eventdetails
Objectdevice
HIDDeviceorigin
string (任意) - デバイスが失効したオリジンです。
HIDDevice.forget()
が呼ばれた後に発生します。 このイベントは、setDevicePermissionHandler
が使用されたときに権限の永続ストレージの維持に利用できます。
イベント: 'select-serial-port'
戻り値:
event
EventportList
SerialPort[]webContents
WebContentscallback
FunctionportId
string
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'
戻り値:
event
Eventport
SerialPortwebContents
WebContents
navigator.serial.requestPort
が呼ばれた後や、select-serial-port
から呼ばれるコールバックが利用可能なる前に新しいシリアルポートが利用可能になると、select-serial-port
が発生します。 このイベントは、UI でユーザーにポートの選択を求め、新しく追加されたポートで UI を更新するために使用することを意図しています。
イベント: 'serial-port-removed'
戻り値:
event
Eventport
SerialPortwebContents
WebContents
navigator.serial.requestPort
が呼ばれたときや、select-serial-port
のコールバックが呼ばれる前にシリアルポートが取り除かれた場合に、select-serial-port
が発生した後に発生します。 このイベントは、UI でユーザーにポートの選択を求め、指定されたポートを取り除いて UI を更新するために使用することを意図しています。
イベント: 'serial-port-revoked'
戻り値:
event
Eventdetails
Objectport
SerialPortframe
WebFrameMainorigin
string - デバイスが失効したオリジンです。
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'
戻り値:
event
Eventdetails
ObjectdeviceList
USBDevice[]frame
WebFrameMain
callback
FunctiondeviceId
string (任意)
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'
戻り値:
event
Eventdevice
USBDevicewebContents
WebContents
navigator.usb.requestDevice
が呼ばれた後や、select-usb-device
から呼ばれるコールバックが利用可能なる前に新しいデバイスが利用可能になると、select-usb-device
が発生します。 このイベントは、UI でユーザーにデバイスの選択を求め、新しく追加されたデバイスで UI を更新するために使用することを意図しています。
イベント: 'usb-device-removed'
戻り値:
event
Eventdevice
USBDevicewebContents
WebContents
navigator.usb.requestDevice
が呼ばれたときや、select-usb-device
のコールバックが呼ばれる前にデバイスが取り除かれた場合に、select-usb-device
が発生した後に発生します。 このイベントは、UI でユーザーにデバイスの選択を求め、指定されたデバイスを取り除いて UI を更新す るために使用することを意図しています。
イベント: 'usb-device-revoked'
戻り値:
event
Eventdetails
Objectdevice
USBDeviceorigin
string (任意) - デバイスが失効したオリジンです。
USBDevice.forget()
が呼ばれた後に発生します。 このイベントは、setDevicePermissionHandler
が使用されたときに権限の永続ストレージの維持に利用できます。
インスタンスメソッド
Session
のインスタンスでは、以下のメソッドが利用できます。
ses.getCacheSize()
戻り値 Promise<Integer>
- バイト単位の、session の現在のキャッシュサイズ。