SOLFIND
Web Lens
Portal home

session | Electron

https://www.electronjs.org/es/docs/latest/api/session • 376 KB fetched
Open original page


session | Electron Saltar al contenido principal Electron Documentación API Blog Herramientas * Electron Forge * Electron Fiddle Comunidad * Gobernanza * Muestra * Recursos Lanzamientos Español * English * Deutsch * Español * Français * 日本語 * Português * Русский * 中文 Búsqueda * Módulos del proceso principal * app * autoUpdater * BaseWindow * BrowserView * Deprecated * BrowserWindow * clipboard * contentTracing * crashReporter * desktopCapturer * dialog * acceso rápido global * ImageView * Compras integradas * ipcMain * Menu * MenuItem * MessageChannelMain * Título 1 Xpath:/h 1 * nativeImage * nativeTheme * net * netLog * Notification * powerMonitor * powerSaveBlocker * process * protocol * pushNotifications * safeStorage * screen * session * sharedTexture * ShareMenu * shell * systemPreferences * Barra táctil * Tray * utilityProcess * webContents * WebContentsView * webFrameMain * Vista * Módulos de Process Renderer * Utility Process Modules * Elementos de DOM personalizados * Chromium y Node.js * Clases * Estructuras del API * * Módulos del proceso principal * session En esta página session Administra las sesiones del navegador, cookies, cache, configuración del proxy, etc. Proceso: principal El módulo session puede ser usado para crear nuevos objetos 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 ( ) ) Métodos ​ El módulo session tiene los siguientes métodos: session.fromPartition(partition[, options]) ​ * partition string * options Object (opcional) * cache boolean - En el caso de activar la memoria cache. Default is true unless the --disable-http-cache switch is used. 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. session.fromPath(path[, options]) ​ * path string * options Object (opcional) * cache boolean - En el caso de activar la memoria cache. Default is true unless the --disable-http-cache switch is used. Returns Session - A session instance from the absolute path as specified by the path string. When there is an existing Session with the same absolute path, it will be returned; otherwise a new Session instance will be created with options . The call will throw an error if the path is not an absolute path. Additionally, an error will be thrown if an empty string is provided. To create a Session with options , you have to ensure the Session with the path has never been used before. No hay manera de cambiar las options de un objeto Session existente. Propiedades ​ El módulo session tiene las siguientes propiedades: session.defaultSession ​ A Session object, the default session object of the app, available after app.whenReady is called. Class: Session ​ Obtener y configurar las propiedades de una sesión. Process: Main This class is not exported from the 'electron' module. 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 Event * item DownloadItem * webContents 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 ( 'node:fs' ) . writeFileSync ( '/somewhere' , response . body ) } ) } ) Evento: 'extension-loaded' ​ Devuelve: * event 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 Event * extension Extension Emitted after an extension is unloaded. This occurs when Session.removeExtension is called. Evento: 'extension-ready' ​ Devuelve: * event 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. Event: 'file-system-access-restricted' ​ Devuelve: * event Event * details Object * origin 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 Function * action string - The action to take as a result of the restricted path access attempt. * allow - This will allow path to be accessed despite restricted status. * deny - This will block the access request and trigger an AbortError . * 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 ( ) } ) Evento: 'preconnect' ​ Devuelve: * event 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 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 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 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 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 Event * details Object * deviceList HIDDevice[] * frame WebFrameMain | null - The frame initiating this event. May be null if accessed after the frame has either navigated or been destroyed. * callback Function * deviceId 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. Additionally, permissioning on navigator.hid can be further managed by using ses.setPermissionCheckHandler(handler) and ses.setDevicePermissionHandler(handler) . const { app , BrowserWindow } = require ( 'electron' ) let win = null app . whenReady ( ) . then ( ( ) => { win = new BrowserWindow ( ) win . webContents . session . setPermissionCheckHandler ( ( webContents , permission , requestingOrigin , details ) => { if ( permission === 'hid' ) { // Add logic here to determine if permission should be given to allow HID selection return true } return false } ) // Optionally, retrieve previously persisted devices from a persistent store const grantedDevices = fetchGrantedDevices ( ) win . webContents . session . setDevicePermissionHandler ( ( details ) => { if ( new URL ( details . origin ) . hostname === 'some-host' && details . deviceType === 'hid' ) { if ( details . device . vendorId === 123 && details . device . productId === 345 ) { // Always allow this type of device (this allows skipping the call to `navigator.hid.requestDevice` first) return true } // Search through the list of devices that have previously been granted permission return grantedDevices . some ( ( grantedDevice ) => { return grantedDevice . vendorId === details . device . vendorId && grantedDevice . productId === details . device . productId && grantedDevice . serialNumber && grantedDevice . serialNumber === details . device . serialNumber } ) } return false } ) win . webContents . session . on ( 'select-hid-device' , ( event , details , callback ) => { event . preventDefault ( ) const selectedDevice = details . deviceList . find ( ( device ) => { return device . vendorId === 9025 && device . productId === 67 } ) callback ( selectedDevice ?. deviceId ) } ) } ) Evento: 'hid-device-added' ​ Devuelve: * event Event * details Object * device HIDDevice * frame WebFrameMain | null - The frame initiating this event. May be null if accessed after the frame has either navigated or been destroyed. Emitted after navigator.hid.requestDevice has been called and select-hid-device has fired if a new device becomes available before the callback from select-hid-device is called. This event is intended for use when using a UI to ask users to pick a device so that the UI can be updated with the newly added device. Evento: 'hid-device-removed' ​ Devuelve: * event Event * details Object * device HIDDevice * frame WebFrameMain | null - The frame initiating this event. May be null if accessed after the frame has either navigated or been destroyed. Emitted after navigator.hid.requestDevice has been called and select-hid-device has fired if a device has been removed before the callback from select-hid-device is called. This event is intended for use when using a UI to ask users to pick a device so that the UI can be updated to remove the specified device. Event: 'hid-device-revoked' ​ Devuelve: * event Event * details Object * device HIDDevice * origin string (optional) - The origin that the device has been revoked from. Emitted after HIDDevice.forget() has been called. This event can be used to help maintain persistent storage of permissions when setDevicePermissionHandler is used. Evento: 'select-serial-port' ​ Devuelve: * event Event * portList SerialPort[] * webContents WebContents * callback Function * portId 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 Event * port SerialPort * webContents WebContents Emitted after navigator.serial.requestPort has been called and select-serial-port has fired if a new serial port becomes available before the callback from select-serial-port is called. This event is intended for use when using a UI to ask users to pick a port so that the UI can be updated with the newly added port. Evento: 'serial-port-removed' ​ Devuelve: * event Event * port SerialPort * webContents WebContents Emitted after navigator.serial.requestPort has been called and select-serial-port has fired if a serial port has been removed before the callback from select-serial-port is called. This event is intended for use when using a UI to ask users to pick a port so that the UI can be updated to remove the specified port. Event: 'serial-port-revoked' ​ Devuelve: * event Event * details Object * port SerialPort * frame WebFrameMain | null - The frame initiating this event. May be null if accessed after the frame has either navigated or been destroyed. * origin string - The origin that the device has been revoked from. Emitted after SerialPort.forget() has been called. This event can be used to help maintain persistent storage of permissions when setDevicePermissionHandler is used. // Browser Process const { app , BrowserWindow } = require ( 'electron' ) app . whenReady ( ) . then ( ( ) => { const win = new BrowserWindow ( { width : 800 , height : 600 } ) win . webContents . session . on ( 'serial-port-revoked' , ( event , details ) => { console . log ( ` Access revoked for serial device from origin ${ details . origin } ` ) } ) } ) // Renderer Process const portConnect = async ( ) => { // Request a port. const port = await navigator . serial . requestPort ( ) // Wait for the serial port to open. await port . open ( { baudRate : 9600 } ) // ...later, revoke access to the serial port. await port . forget ( ) } Event: 'select-usb-device' ​ Devuelve: * event Event * details Object * deviceList USBDevice[] * frame WebFrameMain | null - The frame initiating this event. May be null if accessed after the frame has either navigated or been destroyed. * callback Function * deviceId string (optional) Emitted when a USB device needs to be selected when a call to navigator.usb.requestDevice is made. callback debería ser llamada con el deviceId a ser seleccionado; al no pasar argumentos a callback se cancelará la solicitud. Additionally, permissioning on navigator.usb can be further managed by using ses.setPermissionCheckHandler(handler) and ses.setDevicePermissionHandler(handler) . const { app , BrowserWindow } = require ( 'electron' ) let win = null app . whenReady ( ) . then ( ( ) => { win = new BrowserWindow ( ) win . webContents . session . setPermissionCheckHandler ( ( webContents , permission , requestingOrigin , details ) => { if ( permission === 'usb' ) { // Add logic here to determine if permission should be given to allow USB selection return true } return false } ) // Optionally, retrieve previously persisted devices from a persistent store (fetchGrantedDevices needs to be implemented by developer to

Links found on this page

  1. Saltar al contenido principal [direct]
  2. Electron [direct]
  3. Documentación [direct]
  4. API [direct]
  5. Blog [direct]
  6. Electron Forge [direct]
  7. Electron Fiddle [direct]
  8. Gobernanza [direct]
  9. Muestra [direct]
  10. Recursos [direct]
  11. Lanzamientos [direct]
  12. English [direct]
  13. Deutsch [direct]
  14. Français [direct]
  15. 日本語 [direct]
  16. Português [direct]
  17. Русский [direct]
  18. 中文 [direct]
  19. autoUpdater [direct]
  20. BaseWindow [direct]
  21. BrowserView Deprecated [direct]
  22. BrowserWindow [direct]
  23. clipboard [direct]
  24. contentTracing [direct]
  25. crashReporter [direct]
  26. desktopCapturer [direct]
  27. dialog [direct]
  28. acceso rápido global [direct]
  29. ImageView [direct]
  30. Compras integradas [direct]
  31. ipcMain [direct]
  32. Menu [direct]
  33. MenuItem [direct]
  34. MessageChannelMain [direct]
  35. Título 1 Xpath:/h 1 [direct]
  36. nativeImage [direct]
  37. nativeTheme [direct]
  38. net [direct]
  39. netLog [direct]
  40. Notification [direct]
  41. powerMonitor [direct]
  42. powerSaveBlocker [direct]
  43. process [direct]
  44. protocol [direct]
  45. pushNotifications [direct]
  46. safeStorage [direct]
  47. screen [direct]
  48. sharedTexture [direct]
  49. ShareMenu [direct]
  50. shell [direct]
  51. systemPreferences [direct]
  52. Barra táctil [direct]
  53. Tray [direct]
  54. utilityProcess [direct]
  55. webContents [direct]
  56. WebContentsView [direct]
  57. webFrameMain [direct]
  58. Vista [direct]
  59. Elementos de DOM personalizados [direct]
  60. Chromium y Node.js [direct]
  61. Clases [direct]
  62. Estructuras del API [direct]
  63. principal [direct]
  64. DownloadItem [direct]
  65. Extension [direct]
  66. chrome.runtime.reload() [direct]
  67. AbortError [direct]
  68. spec [direct]
  69. HIDDevice[] [direct]
  70. SerialPort[] [direct]
  71. USBDevice[] [direct]
  72. WebAuthnAccount[] [direct]
  73. ProxyConfig [direct]
  74. Promise<ResolvedHost> [direct]
  75. GlobalRequest [direct]
  76. RequestInit [direct]
  77. Response [direct]
  78. webRequest [direct]
  79. Certificate [direct]
  80. here [direct]