session
Administra las sesiones del navegador, cookies, cache, configuración del proxy, etc.
Proceso: principal</0>
El módulo session
puede ser usado para crear nuevos objetos session
.
También puede acceder el session
de las páginas existentes utilizando la propiedad session
de WebContents
, o desde el módulo session
.
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ width: 800, height: 600 })
win.loadURL('http://github.com')
const ses = win.webContents.session
console.log(ses.getUserAgent())
Métodos
El módulo session
tiene los siguientes métodos:
session.fromPartition(partition[, options])
partition
string
Regresa Session
- Una instancia de session de la cadena partition
. Cuando hay una Session
existente con la misma partition
, se devolverá la misma; de otra manera, una nueva instancia Session
será creada con options
.
Si la partition
comienza con persist:
, la página usará una sesión persistente disponible a todas las páginas en la aplicación con la misma partition
. si no hay un prefijo persist:
, la página usará una sesión en memoria. Si la partition
está vacía entonces la sesión de la aplicación será usada por defecto.
Al crear una Session
con options
, tiene que asegurar que la Session
con la partition
nunca ha sido usada antes. No hay manera de cambiar las options
de un objeto Session
existente.
Propiedades
El módulo session
tiene las siguientes propiedades:
session.defaultSession
Un objeto Session
, es el objeto de session de la aplicación por defecto.
Class: Session
Obtener y configurar las propiedades de una sesión.
Proceso: Main
Esta clase no está exportada desde el módulo 'electron'
. Sólo está disponible como un valor de retorno de otros métodos en la API de Electron.
Puede crear un objeto Session
en el módulo session
:
const { session } = require('electron')
const ses = session.fromPartition('persist:name')
console.log(ses.getUserAgent())
Eventos de Instancia
Los siguientes eventos están disponibles en instancias de Session
:
Evento: 'will-download'
Devuelve:
event
item
DownloadItemwebContents
WebContents
Emitido cuando Electron está por descargar un elemento
en Contenido web
.
Llamando event.preventDefault()
Se cancelará la descarga y el elemento
no estará disponible para el siguiente tick del proceso.
const { session } = require('electron')
session.defaultSession.on('will-download', (event, item, webContents) => {
event.preventDefault()
require('got')(item.getURL()).then((response) => {
require('fs').writeFileSync('/somewhere', response.body)
})
})
Evento: 'extension-loaded'
Devuelve:
event
extension
Extension
Emitted after an extension is loaded. This occurs whenever an extension is added to the "enabled" set of extensions. Esto incluye:
- Extensions being loaded from
Session.loadExtension
. - Extensions being reloaded:
- from a crash.
- if the extension requested it (
chrome.runtime.reload()
).
Evento: 'extension-unloaded'
Devuelve:
event
extension
Extension
Emitted after an extension is unloaded. This occurs when Session.removeExtension
is called.
Evento: 'extension-ready'
Devuelve:
event
extension
Extension
Emitted after an extension is loaded and all necessary browser state is initialized to support the start of the extension's background page.
Evento: 'preconnect'
Devuelve:
event
preconnectUrl
string - The URL being requested for preconnection by the renderer.allowCredentials
boolean - True if the renderer is requesting that the connection include credentials (see the spec for more details.)
Emitido cuando un render process solicita preconexión a una URL, generalmente debido a resource hint.
Evento: 'spellcheck-dictionary-initialized'
Devuelve:
event
languageCode
string - The language code of the dictionary file
Emitted when a hunspell dictionary file has been successfully initialized. This occurs after the file has been downloaded.
Evento: 'spellcheck-dictionary-download-begin'
Devuelve:
event
languageCode
string - The language code of the dictionary file
Emitido cuando un archivo de diccionario hunspell se comienza a descargar
Evento: 'spellcheck-dictionary-download-success'
Devuelve:
event
languageCode
string - The language code of the dictionary file
Emitido cuando un archivo de diccionario hunspell se ha descargado correctamente
Evento: 'spellcheck-dictionary-download-failure'
Devuelve:
event
languageCode
string - The language code of the dictionary file
Emitted when a hunspell dictionary file download fails. For details on the failure you should collect a netlog and inspect the download request.
Event: 'select-hid-device'
Devuelve:
event
details
ObjectdeviceList
HIDDevice[]frame
WebFrameMain
callback
FuncióndeviceId
string | null (optional)
Emitido cuando un dispositivo HID necesita ser seleccionado cuando se realizó una llamada a navigator.hid.requestDevice
. callback
debería ser llamada con el deviceId
a ser seleccionado; al no pasar argumentos a callback
se cancelará la solicitud. Adicionalmente, los permisos en navigator.hid
pueden ser administrados aún más usando ses.setPermissionCheckHandler(handler) y 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') {
// Agregue la lógica aquí para determinar si el permiso debería ser dado para permitir la selección HID
return true
}
return false
})
// Opcionalmente, recupere los dispositivos persistentes anteriormente de un almacén persistente
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) {
// Siempre permite este tipo de dispositivo (esto permite saltar la primera llamada a `navigator.hid.requestDevice`)
return true
}
// Busque a través de la lista de dispositivos a los que anteriormente se le han otorgado permiso
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(selectedPort?.deviceId)
})
})
Evento: 'hid-device-added'
Devuelve:
event
details
Objectdevice
HIDDevice[]frame
WebFrameMain
Emitido cuando un nuevo dispositivo HID está disponible. Por ejemplo, cuando un nuevo dispositivo USB se conecta.
Este evento sólo se emitirá después de que navigator.hid.requestDevice
haya sido llamado y select-hid-device
haya sido disparado.
Evento: 'hid-device-removed'
Devuelve:
event
details
Objectdevice
HIDDevice[]frame
WebFrameMain
Emitido cuando un dispositivo HID ha sido eliminado. For example, this event will fire when a USB device is unplugged.
Este evento sólo se emitirá después de que navigator.hid.requestDevice
haya sido llamado y select-hid-device
haya sido disparado.
Evento: 'select-serial-port'
Devuelve:
event
portList
SerialPort[]webContents
WebContentscallback
FunciónportId
string
Emitted when a serial port needs to be selected when a call to navigator.serial.requestPort
is made. callback
should be called with portId
to be selected, passing an empty string to callback
will cancel the request. Additionally, permissioning on navigator.serial
can be managed by using ses.setPermissionCheckHandler(handler) with the serial
permission.
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)
}
})
})
Evento: 'serial-port-added'
Devuelve:
event
port
SerialPortwebContents
WebContents
Emitted after navigator.serial.requestPort
has been called and select-serial-port
has fired if a new serial port becomes available. For example, this event will fire when a new USB device is plugged in.
Evento: 'serial-port-removed'
Devuelve:
event
port
SerialPortwebContents
WebContents
Emitted after navigator.serial.requestPort
has been called and select-serial-port
has fired if a serial port has been removed. For example, this event will fire when a USB device is unplugged.
Métodos de Instancia
Los siguientes métodos están disponibles para instancias de Sesión
:
ses.getCacheSize()
Devuelve Promise<Integer>
- El tamaño de cache de la sesión actual, en bytes.
ses.clearCache()
Devuelve Promise<void>
- Se resuelve cuando la operación de limpieza de cache es completada.
Borra la memoria caché del HTTP de la sesión.
ses.clearStorageData([options])
Devuelve Promise<void>
- Se resuelve cuando los datos del almacenamiento ha sido borrado.
ses.flushStorageData()
Escribe cualquier dato DOMStorage que no lo haya sido en disco.
ses.setProxy(config)
config
Objectmode
string (optional) - The proxy mode. Should be one ofdirect
,auto_detect
,pac_script
,fixed_servers
orsystem
. If it's unspecified, it will be automatically determined based on other specified options.direct
In direct mode all connections are created directly, without any proxy involved.auto_detect
In auto_detect mode the proxy configuration is determined by a PAC script that can be downloaded at http://wpad/wpad.dat.pac_script
In pac_script mode the proxy configuration is determined by a PAC script that is retrieved from the URL specified in thepacScript
. This is the default mode ifpacScript
is specified.fixed_servers
In fixed_servers mode the proxy configuration is specified inproxyRules
. This is the default mode ifproxyRules
is specified.system
In system mode the proxy configuration is taken from the operating system. Note that the system mode is different from setting no proxy configuration. In the latter case, Electron falls back to the system settings only if no command-line options influence the proxy configuration.
pacScript
string (optional) - The URL associated with the PAC file.proxyRules
string (optional) - Rules indicating which proxies to use.proxyBypassRules
string (optional) - Rules indicating which URLs should bypass the proxy settings.
Devuelve Promise<void>
- Se resuelve cuando el proceso de configuración del proxy está completo.
Configurar proxy.
When mode
is unspecified, pacScript
and proxyRules
are provided together, the proxyRules
option is ignored and pacScript
configuration is applied.
You may need ses.closeAllConnections
to close currently in flight connections to prevent pooled sockets using previous proxy from being reused by future requests.
Las proxyRules
tienen las siguientes reglas abajo:
proxyRules = schemeProxies[";"<schemeProxies>]
schemeProxies = [<urlScheme>"="]<proxyURIList>
urlScheme = "http" | "https" | "ftp" | "socks"
proxyURIList = <proxyURL>[","<proxyURIList>]
proxyURL = [<proxyScheme>"://"]<proxyHost>[":"<proxyPort>]
Por ejemplo:
http=foopy:80;ftp=foopy2
- Usa proxy HTTPfoopy:80
para URLhttp://
, HTTP proxyfoopy2:80
para URLftp://
.foopy:80
- Usa Proxy HTTPfoopy:80
para todas las URLs.foopy:80,bar,direct://
- Usa proxy HTTPfoopy:80
para todas las URLs, no sobrebar
sifoopy:80
no está disponible, y después de eso no usar ningún proxy.socks4://foopy
- Usa SOCKS v4 proxyfoopy:1080
para todas las URLs.http=foopy,socks5://bar.com
- Usa HTTP proxyfoopy
para las URLs http, y falla para el proxy SOCKS5bar.com
sifoopy
no está disponible.http=foopy,direct://
- Usa el proxy HTTPfoopy
para URLs http, y no usa el proxy sifoopy
no está disponible.http=foopy;socks=foopy2
- Usa el proxy HTTPfoopy
para URLs HTTP, y usasocks4://foopy2
para el resto de URLs.
El proxyBypassRules
es una lista separada por comas de las reglasa que se describen a continuación:
[ URL_SCHEME "://" ] HOSTNAME_PATTERN [ ":" <port> ]
Une todos los nombres que coinciden con el patrón HOSTNAME_PATTERN.
Examples: "foobar.com", "foobar.com", ".foobar.com", "foobar.com:99", "https://x..y.com:99"
"." HOSTNAME_SUFFIX_PATTERN [ ":" PORT ]
Une sufijos de dominios particulares.
Examples: ".google.com", ".com", "http://.google.com"
[ SCHEME "://" ] IP_LITERAL [ ":" PORT ]
Une URLs que son literales de dirección IP.
Ejemplos: "127.0.1", "[0:0::1]", "[::1]", "http://[::1]:99"
IP_LITERAL "/" PREFIX_LENGTH_IN_BITS
Match any URL that is to an IP literal that falls between the given range. IP range is specified using CIDR notation.
Ejemplos: "192.168.1.1/16", "fefe:13::abc/33".
<local>
Match local addresses. The meaning of
<local>
is whether the host matches one of: "127.0.0.1", "::1", "localhost".
ses.resolveProxy(url)
url
URL
Devuelve Promise<string>
- Se resuelve con la información del proxy para url
.
ses.forceReloadProxyConfig()
Returns Promise<void>
- Resolves when the all internal states of proxy service is reset and the latest proxy configuration is reapplied if it's already available. The pac script will be fetched from pacScript
again if the proxy mode is pac_script
.
ses.setDownloadPath(path)
path
string - The download location.
Sets download saving directory. By default, the download directory will be the Downloads
under the respective app folder.
ses.enableNetworkEmulation(options)
Emula la red con la configuración dada por la sesión
.
Para emular la conexión GPRS con rendimiento de 50kbps y latencia de 500ms.
window.webContents.session.enableNetworkEmulation({
latency: 500,
downloadThroughput: 6400,
uploadThroughput: 6400
})
// Para emular la caída de la red.
window.webContents.session.enableNetworkEmulation({ offline: true })
ses.preconnect(options)
Preconecta el número dado de sockets a un origen.
ses.closeAllConnections()
Returns Promise<void>
- Resolves when all connections are closed.
Note: It will terminate / fail all requests currently in flight.
ses.disableNetworkEmulation()
Disables any network emulation already active for the session
. Resets to the original network configuration.
ses.setCertificateVerifyProc(proc)
proc
Function | null- Objeto
request
hostname
stringcertificate
certificatevalidatedCertificate
CertificateisIssuedByKnownRoot
boolean -true
if Chromium recognises the root CA as a standard root. If it isn't then it's probably the case that this certificate was generated by a MITM proxy whose root has been installed locally (for example, by a corporate proxy). No podrás confiar en el resultado si elverificationResult
no aparece comoOK
.verificationResult
string -OK
if the certificate is trusted, otherwise an error likeCERT_REVOKED
.errorCode
Integer - Código de error.
callback
FunciónverificationResult
Integer - Value can be one of certificate error codes from here. Apart from the certificate error codes, the following special codes can be used.0
- Indica éxito y deshabilita la verificación Certificate Transparency.-2
- Indica falla.-3
- Usa el resultado de verificación de chromium.
- Objeto
Establece el certificado de verificar proc de la sesión
, el proc
será cancelada con proc(request, callback)
cuando sea solicitado una verificación del certificado del servidor. Llamando callback(0)
se acepta el certificado, llamando callback(-2)
se rechaza.
Llamando setCertificateVerifyProc(null)
se reveritrá la verificación de certificado por defecto.
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)
}
})
NOTE: The result of this procedure is cached by the network service.
ses.setPermissionRequestHandler(handler)
handler
Function | nullcontenido web
contenido web - contenido web solicitando el permiso. Por favor, tenga en cuenta que si la solicitud viene de un subframe debe utilizarrequestUrl
para comprobar el origen de la solicitud.permission
string - The type of requested permission.clipboard-read
- Request access to read from the clipboard.media
- Request access to media devices such as camera, microphone and speakers.display-capture
- Solicita acceso para capturar la pantalla.mediaKeySystem
- Request access to DRM protected content.geolocation
- Request access to user's current location.notifications
- Request notification creation and the ability to display them in the user's system tray.midi
- Request MIDI access in thewebmidi
API.midiSysex
- Request the use of system exclusive messages in thewebmidi
API.pointerLock
- Request to directly interpret mouse movements as an input method. Pulse aquí para saber más.fullscreen
- Request for the app to enter fullscreen mode.openExternal
- Request to open links in external applications.unknown
- Una solicitud de premiso no reconocida
callback
FunciónpermissionGranted
boolean - Allow or deny the permission.
details
Object - Some properties are only available on certain permission types.externalURL
string (optional) - The url of theopenExternal
request.securityOrigin
string (optional) - The security origin of themedia
request.mediaTypes
string[] (optional) - The types of media access being requested, elements can bevideo
oraudio
requestingUrl
string - The last URL the requesting frame loadedisMainFrame
boolean - Whether the frame making the request is the main frame
Configurar el controlador que será usado para responder las peticiones de permisos para la sesión
. Llamando callback(true)
se permitirá el permiso y callback(false)
se rechazará. Para limpiar el manejador, llamar a setPermissionRequestHandler(null)
. Por favor, tenga en cuenta que debe implementar también setPermissionCheckHandler
para obtener el manejo completo de los permisos. La mayoría de las APIs web hacen una verificación de permiso y luego hacen una solicitud de permiso si la verificación es denegada.
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 verificando el permiso. Por favor, tenga en cuenta que si la solicitud viene de un subframe debe utilizarrequestUrl
para comprobar el origen de la solicitud. Todos los sub frames de origen cruzado que realizan comprobaciones de permisos pasarán un webContentsnull
a este controlador, mientras que otras comprobaciones de permisos, comonotifications
siempre pasaránnull
. Debería usarembeddingOrigin
yrequestingOrigin
para determinar que origen se encuentra en el marco propietario y en el marco solicitante respectivamente.permission
string - Type of permission check. Los valores permitidos sonmidiSysex
,notifications
,geolocation
,media
,mediaKeySystem
,midi
,pointerLock
,fullscreen
,openExternal
,hid
, oserial
.requestingOrigin
string - The origin URL of the permission checkdetails
Object - Some properties are only available on certain permission types.embeddingOrigin
string (optional) - The origin of the frame embedding the frame that made the permission check. Sólo se establece cross-origin submarcos haciendo comprobaciones de permisos.securityOrigin
string (optional) - The security origin of themedia
check.mediaType
string (optional) - The type of media access being requested, can bevideo
,audio
orunknown
requestingUrl
string (optional) - The last URL the requesting frame loaded. Esto no es proveído para cross-origin submarcos haciendo comprobaciones de permiso.isMainFrame
boolean - Whether the frame making the request is the main frame
Establece el manejador que puede ser usado para responder a las comprobaciones para session
. Retornando true
permitirá el permiso y false
lo rechará. Por favor, tenga en cuenta que debe implementar también setPermissionRequestHandler
para obtener el manejo completo de los permisos. La mayoría de las APIs web hacen una verificación de permiso y luego hacen una solicitud de permiso si la verificación es denegada. Para borrar el manejador, llame 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 // concedido
}
return false // denegado
})
ses.setDevicePermissionHandler(handler)
handler
Function\<boolean> | nulldetails
ObjectdeviceType
string - The type of device that permission is being requested on, can behid
orserial
.origin
string - The origin URL of the device permission check.device
HIDDevice | SerialPort- the device that permission is being requested for.frame
WebFrameMain - WebFrameMain comprobando el permiso del dispositivo.
Establece el manejador que puede ser usado para responder a las comprobaciones de permiso para la session
. Devolver true
permitirá que el dispositivo se permitido y false
lo rechazará. Para borrar el manejador, llame a setDevicePermissionHandler(null)
. Este manejador puede ser usado para otorgar permisos por defecto a dispositivos sin solicitar primero el permiso a dispositivos (por ejemplo a través de navigator.hid.requestDevice
). Si este manejador no esta definido, los permisos por defecto para el dispositivo serán otorgados a través de la selección de dispositivo (por ejemplo a través de navigator.hid.requestDevice
). Adicionalmente, el comportamiento por defecto de Electron es almacenar los permisos otorgados a dispositivos a través de toda la vida del correspondiente WebContents. Si se es necesario almacenarlo a más largo plazo, un desarrollador puede almacenar los permisos otorgados (por ejemplo, cuando se maneja el evento select-hid-device
) y luego leerlo desde ese almacenamiento con 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
}
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(selectedPort?.deviceId)
})
})
ses.clearHostResolverCache()
Devuelve Promise<void>
- Se resuelve cuando la operación es completada.
Borra la caché de resolución de host.
ses.allowNTLMCredentialsForDomains(domains)
domains
string - A comma-separated list of servers for which integrated authentication is enabled.
Configura dinámicamente cada vez que se envíen credenciales para HTTP NTLM o negociaciones de autenticación.
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
cadenaacceptLanguages
string (optional)
Reemplaza el userAgent
y los lenguajes aceptados
para esta sesión.
Los lenguajes aceptados
deben estar ordenados en una lista separada por coma de códigos de lenguaje, por ejemplo "en-US,fr,de,ko,zh-CN,ja"
.
Esto no afecta el contenido web
existente, y cada contenido web
puede usar webContents.setUserAgent
para sobreescribir el agente de sesión de usuario.
ses.isPersistent()
Returns boolean
- Whether or not this session is a persistent one. The default webContents
session of a BrowserWindow
is persistent. When creating a session from a partition, session prefixed with persist:
will be persistent, while others will be temporary.
ses.getUserAgent()
Returns string
- The user agent for this session.
ses.setSSLConfig(config)
config
ObjectminVersion
string (optional) - Can betls1
,tls1.1
,tls1.2
ortls1.3
. The minimum SSL version to allow when connecting to remote servers. Por defecto atls1
.maxVersion
string (optional) - Can betls1.2
ortls1.3
. The maximum SSL version to allow when connecting to remote servers. Por defecto estls1.3
.disabledCipherSuites
Integer[] (optional) - List of cipher suites which should be explicitly prevented from being used in addition to those disabled by the net built-in policy. Supported literal forms: 0xAABB, where AA iscipher_suite[0]
and BB iscipher_suite[1]
, as defined in RFC 2246, Section 7.4.1.2. Unrecognized but parsable cipher suites in this form will not return an error. Ex: To disable TLS_RSA_WITH_RC4_128_MD5, specify 0x0004, while to disable TLS_ECDH_ECDSA_WITH_RC4_128_SHA, specify 0xC002. Note that TLSv1.3 ciphers cannot be disabled using this mechanism.
Sets the SSL configuration for the session. All subsequent network requests will use the new configuration. Existing network connections (such as WebSocket connections) will not be terminated, but old sockets in the pool will not be reused for new connections.
ses.getBlobData(identifier)
identifier
string - Valid UUID.
Devuelve Promise<Buffer>
- Se resuelve con datos blob.
ses.downloadURL(url)
url
string
Inicia una descargar del recurso en url
. La API generará un DownloadItem que puede ser accedido con el evento will-download.
Note: Esto no realiza ninguna comprobación de seguridad relacionada con la pagina de origen a diferencia de webContents.downloadURL
.
ses.createInterruptedDownload(options)
Permite cancelar
o interrumpir
descargas de una Sesión
previa. La API generará un elemento de descarga que puede ser accesado con el evento se descargará. El Elemento de descarga no tendrá ningún contenido web
asociado con el y el estado inicial será interrumpido
. La descarga empezará solo cuando la reanudación
de la API sea llamada en el elemento descargado.
ses.clearAuthCache()
Devuelve Promise<void>
- resuelve cuando se ha borrado el caché de autenticación HTTP de la sesión.
ses.setPreloads(preloads)
preloads
string[] - An array of absolute path to preload scripts
Agrega scripts que se ejecutarán en TODOS los contenidos web que están asociados con esta sesión justo antes de que se ejecuten los scripts de preload
normales.
ses.getPreloads()
Returns string[]
an array of paths to preload scripts that have been registered.
ses.setCodeCachePath(path)
path
String - Absolute path to store the v8 generated JS code cache from the renderer.
Sets the directory to store the generated JS code cache for this session. The directory is not required to be created by the user before this call, the runtime will create if it does not exist otherwise will use the existing directory. If directory cannot be created, then code cache will not be used and all operations related to code cache will fail silently inside the runtime. By default, the directory will be Code Cache
under the respective user data folder.
ses.clearCodeCaches(options)
Returns Promise<void>
- resolves when the code cache clear operation is complete.
ses.setSpellCheckerEnabled(enable)
enable
boolean
Sets whether to enable the builtin spell checker.
ses.isSpellCheckerEnabled()
Returns boolean
- Whether the builtin spell checker is enabled.
ses.setSpellCheckerLanguages(idiomas)
languages
string[] - An array of language codes to enable the spellchecker for.
El corrector ortográfico integrado no detecta automáticamente en que idioma un usuario esta escribiendo. Para que el corrector ortográfico compruebe correctamente sus palabras, usted debe llamar a esta API con un array de códigos de idiomas. Usted puede obtener la lista de los códigos de idiomas soportados con la propiedad ses.availableSpellCheckerLanguages
.
Note: On macOS the OS spellchecker is used and will detect your language automatically. This API is a no-op on macOS.
ses.getSpellCheckerLanguages()
Returns string[]
- An array of language codes the spellchecker is enabled for. Si esta lista está vacía, el corrector ortográfico volverá a usar en-US
. Por defecto al iniciar si esta lista de opción es una lista vacía Electron tratará de llenar esta opción con el locale actual del sistema operativo. Este configuración es persistente entre reinicios.
Note: On macOS the OS spellchecker is used and has its own list of languages. This API is a no-op on macOS.
ses.setSpellCheckerDictionaryDownloadURL(url)
url
string - A base URL for Electron to download hunspell dictionaries from.
Por defecto Electron descargará diccionarios hunspell desde la CDN de Chromium. Si usted quiere sobrescribir este comportamiento puede usar esta API para apuntar el descargador de diccionarios a su propia versión alojada de diccionarios hunspell. We publish a hunspell_dictionaries.zip
file with each release which contains the files you need to host here.
The file server must be case insensitive. If you cannot do this, you must upload each file twice: once with the case it has in the ZIP file and once with the filename as all lowercase.
Si los archivos presentes en hunspell_dictionaries.zip
están disponible en https://example.com/dictionaries/language-code.bdic
entonces entonces debería llamar esta api con ses.setSpellCheckerDictionaryDownloadURL('https://example.com/dictionaries/')
. Por favor, tenga en cuenta la barra final. La URL a los diccionarios esta formada como ${url}${filename}
.
Note: On macOS the OS spellchecker is used and therefore we do not download any dictionary files. This API is a no-op on macOS.
ses.listWordsInSpellCheckerDictionary()
Returns Promise<string[]>
- An array of all words in app's custom dictionary. Resolves when the full dictionary is loaded from disk.
ses.addWordToSpellCheckerDictionary(palabra)
word
string - The word you want to add to the dictionary
Returns boolean
- Whether the word was successfully written to the custom dictionary. Esta API no funcionará en sesiones no persistentes (en-memoría).
Note: On macOS and Windows 10 this word will be written to the OS custom dictionary as well
ses.removeWordFromSpellCheckerDictionary(word)
word
string - The word you want to remove from the dictionary
Returns boolean
- Whether the word was successfully removed from the custom dictionary. Esta API no funcionará en sesiones no persistentes (en-memoría).
Note: On macOS and Windows 10 this word will be removed from the OS custom dictionary as well
ses.loadExtension(path[, options])
path
string - Path to a directory containing an unpacked Chrome extension
Devuelve Promise<Extension>
- se resuelve cuando la extensión está cargada.
This method will raise an exception if the extension could not be loaded. If there are warnings when installing the extension (e.g. if the extension requests an API that Electron does not support) then they will be logged to the console.
Note that Electron does not support the full range of Chrome extensions APIs. See Supported Extensions APIs for more details on what is supported.
Note that in previous versions of Electron, extensions that were loaded would be remembered for future runs of the application. This is no longer the case: loadExtension
must be called on every boot of your app if you want the extension to be loaded.
const { app, session } = require('electron')
const path = require('path')
app.on('ready', 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.
})
This API does not support loading packed (.crx) extensions.
Note: This API cannot be called before the ready
event of the app
module is emitted.
Note: Loading extensions into in-memory (non-persistent) sessions is not supported and will throw an error.
ses.removeExtension(extensionId)
extensionId
string - ID of extension to remove
Descarga una extensión.
Note: This API cannot be called before the ready
event of the app
module is emitted.
ses.getExtension(extensionId)
extensionId
string - ID of extension to query
Devuelve Extension
| null
- La extensión cargada con el ID dado.
Note: This API cannot be called before the ready
event of the app
module is emitted.
ses.getAllExtensions()
Devuelve Extension[]
- Una lista de todas las extensiones cargadas.
Note: This API cannot be called before the ready
event of the app
module is emitted.
ses.getStoragePath()
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
.
Propiedades de la instancia
Las siguientes propiedades están disponibles en instancias de Sesión
:
ses.availableSpellCheckerLanguages
Readonly
Un array string[]
que consiste en todos los idiomas conocidos disponibles para el corrector ortográfico. Proporcionar un código de lenguaje a la API setSpellCheckerLanguages
que no este en este array resultará en un error.
ses.spellCheckerEnabled
A boolean
indicating whether builtin spell checker is enabled.
ses.storagePath
SoloLectura
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
Readonly
Un objeto Cookies
para esta sesión.
ses.serviceWorkers
SoloLectura
Un objeto ServiceWorkers
para esta sesión.
ses.webRequest
Readonly
Un objeto WebRequest
para esta sesión.
ses.protocol
Readonly
Un objeto Protocol
para esta sesión.
const { app, session } = require('electron')
const path = require('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(`${__dirname}/${url}`) })
})) {
console.error('Failed to register protocol')
}
})
ses.netLog
Readonly
Un objeto NetLog
para esta sesión.
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)
})