What is a Session
A Session object manages browser sessions, cookies, cache, proxy settings, and related functionality. Sessions are created through the session module using methods like session.fromPartition() or session.fromPath(). A Session is not directly exported from the 'electron' module but is returned by other Electron API methods. The session object is accessible from existing pages via the session property of WebContents or from the session module itself.
session.defaultSession property
session.defaultSession is a Session object representing the default session object of the app. It is available after app.whenReady is called.
session.fromPartition() method signature and behavior
session.fromPartition(partition[, options]) creates or returns a Session instance. Parameters: partition (string, required) - the partition identifier; options (Object, optional) with property cache (boolean, default true unless --disable-http-cache switch is used). If partition starts with 'persist:', the page uses a persistent session available to all pages with the same partition. Without 'persist:' prefix, the page uses an in-memory session. An empty partition returns the app's default session. When there is an existing Session with the same partition, it is returned; otherwise a new Session is created with options. To create a Session with options, ensure the partition has never been used before; there is no way to change the options of an existing Session object.
session.fromPath() method signature and behavior
session.fromPath(path[, options]) creates or returns a Session instance from an absolute path. Parameters: path (string, required) - the absolute path; options (Object, optional) with property cache (boolean, default true unless --disable-http-cache switch is used). The method will throw an error if the path is not an absolute path or if an empty string is provided. When there is an existing Session with the same absolute path, it is returned; otherwise a new Session is created with options. To create a Session with options, ensure the path has never been used before; there is no way to change the options of an existing Session object.
ses.getCacheSize() method
ses.getCacheSize() returns Promise<Integer> - the session's current cache size, in bytes.
ses.clearCache() method
ses.clearCache() returns Promise<void> - resolves when the cache clear operation is complete. Clears the session's HTTP cache.
ses.clearStorageData() method signature and options
ses.clearStorageData([options]) clears storage data and returns Promise<void>. Options parameter is an optional Object with: origin (string, optional) - should follow window.location.origin's representation scheme://host:port; storages (string[], optional) - types of storages to clear: 'cookies', 'filesystem', 'indexdb', 'localstorage', 'shadercache', 'serviceworkers', 'cachestorage'. If storages is not specified, all storage types are cleared.
ses.flushStorageData() method
ses.flushStorageData() writes any unwritten DOMStorage data to disk.
ses.setUserAgent() method
ses.setUserAgent(userAgent[, acceptLanguages]) overrides the userAgent and acceptLanguages for this session. userAgent is a string; acceptLanguages is an optional comma-separated ordered list of language codes, for example 'en-US,fr,de,ko,zh-CN,ja'. Does not affect existing WebContents; each WebContents can use webContents.setUserAgent to override the session-wide user agent.
ses.isPersistent() method
ses.isPersistent() returns boolean - whether this session is persistent. The default webContents session of a BrowserWindow is persistent. When creating a session from a partition, sessions prefixed with 'persist:' are persistent, while others are temporary.
ses.getUserAgent() method
ses.getUserAgent() returns string - the user agent for this session.
Example: Access session from WebContents
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())
Example: Create Session from partition
const { session } = require('electron')
const ses = session.fromPartition('persist:name')
console.log(ses.getUserAgent())
Example: Handle will-download event
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)
})
})
ses.clearAuthCache() clears HTTP authentication cache
The ses.clearAuthCache() method returns Promise<void> and resolves when the session's HTTP authentication cache has been cleared.
ses.setCodeCachePath() configures code cache directory
The ses.setCodeCachePath(path) method accepts a string path (absolute path to store v8 generated JS code cache from the renderer). It sets the directory to store generated JS code cache for this session. The directory is not required to exist before the call; the runtime will create it if it does not exist or will use the existing directory. If the directory cannot be created, code cache will not be used and all operations will fail silently. By default, the directory is 'Code Cache' under the respective user data folder. Note that by default code cache is only enabled for http(s) URLs; to enable code cache for custom protocols, both codeCache: true and standard: true must be specified when registering the protocol.
ses.clearCodeCaches() removes code cache entries
The ses.clearCodeCaches(options) method accepts an options object with urls (String[], optional) - an array of URLs corresponding to resources whose generated code cache needs to be removed. If the list is empty, all entries in the cache directory will be removed. Returns Promise<void> that resolves when the code cache clear operation is complete.
ses.getSharedDictionaryUsageInfo() returns shared dictionary storage info
The ses.getSharedDictionaryUsageInfo() method 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 with Brotli and ZStandard. For detailed information about a specific entry, call getSharedDictionaryInfo(options).
ses.getSharedDictionaryInfo() parameters for frame and site context
The ses.getSharedDictionaryInfo(options) method accepts an options object with frameOrigin (string, required) - the origin of the frame where the request originates, defined by scheme, host, and port; and topFrameSite (string, required) - the site of the top-level browsing context (main frame or tab containing the request). Returns Promise<SharedDictionaryInfo[]> - an array of shared dictionary information entries. To get information about all present shared dictionaries, call getSharedDictionaryUsageInfo().
ses.clearSharedDictionaryCache() clears dictionary cache in memory and on disk
The ses.clearSharedDictionaryCache() method returns Promise<void> that resolves when the dictionary cache has been cleared, both in memory and on disk.
ses.clearSharedDictionaryCacheForIsolationKey() clears cache for specific isolation key
The ses.clearSharedDictionaryCacheForIsolationKey(options) method accepts an options object with frameOrigin (string) and topFrameSite (string) to specify the isolation key. Returns Promise<void> that resolves when the dictionary cache has been cleared for the specified isolation key, both in memory and on disk.
ses.setSpellCheckerEnabled() enables or disables spell checker
The ses.setSpellCheckerEnabled(enable) method accepts a boolean parameter and sets whether to enable the builtin spell checker.
ses.isSpellCheckerEnabled() returns spell checker status
The ses.isSpellCheckerEnabled() method returns a boolean indicating whether the builtin spell checker is enabled.
ses.setSpellCheckerLanguages() sets languages for spell checker
The ses.setSpellCheckerLanguages(languages) method accepts a string array of language codes to enable the spellchecker for. The builtin spellchecker does not automatically detect the language a user is typing in; you must call this API with an array of language codes for the spell checker to correctly check words. Available language codes can be obtained from the ses.availableSpellCheckerLanguages property. On macOS, the OS spellchecker is used and will detect language automatically; this API is a no-op on macOS.
ses.getSpellCheckerLanguages() returns enabled spell checker languages
The ses.getSpellCheckerLanguages() method returns a string array of language codes the spellchecker is enabled for. If the list is empty, the spellchecker will fallback to en-US. By default on launch, if this setting is empty, Electron will try to populate it with the current OS locale. This setting is persisted across restarts. On macOS, the OS spellchecker is used and this API will return whichever languages have been configured by the OS.
ses.setSpellCheckerDictionaryDownloadURL() overrides hunspell dictionary source
The ses.setSpellCheckerDictionaryDownloadURL(url) method accepts a string URL - a base URL for Electron to download hunspell dictionaries from. By default, Electron downloads from the Chromium CDN. Use this to point the dictionary downloader at your own hosted version. Electron publishes a hunspell_dictionaries.zip file with each release containing the files to host. The file server must be case insensitive; if not, upload each file twice: once with the case in the ZIP and once with the filename in all lowercase. If files are at https://example.com/dictionaries/language-code.bdic, call this with 'https://example.com/dictionaries/' (note the trailing slash). The URL is formed as ${url}${filename}. On macOS, the OS spellchecker is used, so this API is a no-op.
ses.listWordsInSpellCheckerDictionary() returns custom dictionary words
The ses.listWordsInSpellCheckerDictionary() method returns Promise<string[]> - an array of all words in the app's custom dictionary. It resolves when the full dictionary is loaded from disk.
ses.addWordToSpellCheckerDictionary() adds word to custom dictionary
The ses.addWordToSpellCheckerDictionary(word) method accepts a string word and adds it to the dictionary. Returns a boolean indicating whether the word was successfully written to the custom dictionary. This API will not work on non-persistent (in-memory) sessions. On macOS and Windows, the word will also be written to the OS custom dictionary.
ses.removeWordFromSpellCheckerDictionary() removes word from custom dictionary
The ses.removeWordFromSpellCheckerDictionary(word) method accepts a string word and removes it from the custom dictionary. Returns a boolean indicating whether the word was successfully removed. This API will not work on non-persistent (in-memory) sessions. On macOS and Windows, the word will also be removed from the OS custom dictionary.
ses.getStoragePath() returns session data directory
The ses.getStoragePath() method returns string | null - the absolute file system path where data for this session is persisted on disk. For in-memory sessions, this returns null.
ses.clearData() clears various types of session data
The ses.clearData([options]) method accepts an options object (optional) with the following properties: dataTypes (String[], optional) - types of data to clear (by default clears all types), can include: backgroundFetch, cache (includes cachestorage and shadercache), cookies, downloads, fileSystems, indexedDB, localStorage, serviceWorkers, webSQL; origins (String[], optional) - clear data for only these origins (cannot be used with excludeOrigins); excludeOrigins (String[], optional) - clear data for all origins except these ones (cannot be used with origins); avoidClosingConnections (boolean, optional) - skips deleting cookies that would close current network connections (default: false); originMatchingMode (String, optional) - behavior for matching data to origins with options 'third-parties-included' (default) or 'origin-in-all-contexts'. Returns Promise<void> that resolves when all data has been cleared. This method is more thorough than clearStorageData. Note that cookies are stored at registrable domain level, so clearing for origin 'https://really.specific.origin.example.com/' clears all cookies for 'example.com'. Clearing cache data also clears the shared dictionary cache; use clearSharedDictionaryCache if you want to clear only the dictionary cache.
ses.availableSpellCheckerLanguages property lists supported languages
The ses.availableSpellCheckerLanguages property is a readonly string array consisting of all known available spell checker languages. Providing a language code to the setSpellCheckerLanguages API that is not in this array will result in an error.
ses.spellCheckerEnabled property indicates spell checker status
The ses.spellCheckerEnabled property is a boolean indicating whether builtin spell checker is enabled.
ses.storagePath property returns session storage directory
The ses.storagePath property is readonly and returns a string | null indicating the absolute file system path where data for this session is persisted on disk. For in-memory sessions, this returns null.
ses.cookies property provides Cookies object for session
The ses.cookies property is readonly and provides a Cookies object for this session.
ses.serviceWorkers property provides ServiceWorkers object for session
The ses.serviceWorkers property is readonly and provides a ServiceWorkers object for this session.
ses.webRequest property provides WebRequest object for session
The ses.webRequest property is readonly and provides a WebRequest object for this session.
ses.protocol property provides Protocol object for registering custom protocols
The ses.protocol property is readonly and provides a Protocol object for this session. This allows registering custom protocols. Example: 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 property provides NetLog object for session logging
The ses.netLog property is readonly and provides a NetLog object for this session. Example: 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);