SOLFIND
Web Lens
Portal home

Device Access | Electron

https://www.electronjs.org/ru/docs/latest/tutorial/devices • 275 KB fetched
Open original page


Device Access | Electron Перейти к основному содержанию Electron Документация API Блог Инструменты * Electron Forge * Electron Fiddle Сообщество * Управление * Примеры * Ресурсы Релизы Русский * English * Deutsch * Español * Français * 日本語 * Português * Русский * 中文 Поиск * Начать * Процессы в Electron * Рекомендации * Примеры * Темный режим * Device Access * In-App Purchases * * Горячие клавиши * Deep Links * Desktop Launcher Actions * * Menus * Многопоточность * Нативное перемещение файла * История навигации * Notification (Оповещения) * Закадровый рендеринг * Обнаружение Online/Offline событий * Progress Bars * Недавние документы * * * Representing Files in a BrowserWindow * * SpellChecker * Web Embeds * Taskbar Customization * * Window Customization * Разработка * Native Node Modules * Распространение * Тестирование и отладка * Ссылки * Вклад * * Примеры * Device Access На этой странице Device Access Like Chromium based browsers, Electron provides access to device hardware through web APIs. For the most part these APIs work like they do in a browser, but there are some differences that need to be taken into account. The primary difference between Electron and browsers is what happens when device access is requested. In a browser, users are presented with a popup where they can grant access to an individual device. In Electron APIs are provided which can be used by a developer to either automatically pick a device or prompt users to pick a device via a developer created interface. Web Bluetooth API ​ The Web Bluetooth API can be used to communicate with bluetooth devices. In order to use this API in Electron, developers will need to handle the select-bluetooth-device event on the webContents associated with the device request. Additionally, ses.setBluetoothPairingHandler(handler) can be used to handle pairing to bluetooth devices on Windows or Linux when additional validation such as a pin is needed. Пример ​ This example demonstrates an Electron application that automatically selects the first available bluetooth device when the Test Bluetooth button is clicked. docs/fiddles/features/web-bluetooth ( 43.4.0 ) Open in Fiddle * main.js * preload.js * index.html * renderer.js const { app , BrowserWindow , ipcMain } = require ( 'electron/main' ) const path = require ( 'node:path' ) let bluetoothPinCallback let selectBluetoothCallback function createWindow ( ) { const mainWindow = new BrowserWindow ( { width : 800 , height : 600 , webPreferences : { preload : path . join ( __dirname , 'preload.js' ) } } ) mainWindow . webContents . on ( 'select-bluetooth-device' , ( event , deviceList , callback ) => { event . preventDefault ( ) selectBluetoothCallback = callback const result = deviceList . find ( ( device ) => { return device . deviceName === 'test' } ) if ( result ) { callback ( result . deviceId ) } else { // The device wasn't found so we need to either wait longer (eg until the // device is turned on) or until the user cancels the request } } ) ipcMain . on ( 'cancel-bluetooth-request' , ( event ) => { selectBluetoothCallback ( '' ) } ) // Listen for a message from the renderer to get the response for the Bluetooth pairing. ipcMain . on ( 'bluetooth-pairing-response' , ( event , response ) => { bluetoothPinCallback ( response ) } ) mainWindow . webContents . session . setBluetoothPairingHandler ( ( details , callback ) => { bluetoothPinCallback = callback // Send a message to the renderer to prompt the user to confirm the pairing. mainWindow . webContents . send ( 'bluetooth-pairing-request' , details ) } ) mainWindow . loadFile ( 'index.html' ) } app . whenReady ( ) . then ( ( ) => { createWindow ( ) app . on ( 'activate' , function ( ) { if ( BrowserWindow . getAllWindows ( ) . length === 0 ) createWindow ( ) } ) } ) app . on ( 'window-all-closed' , function ( ) { if ( process . platform !== 'darwin' ) app . quit ( ) } ) const { contextBridge , ipcRenderer } = require ( 'electron/renderer' ) contextBridge . exposeInMainWorld ( 'electronAPI' , { cancelBluetoothRequest : ( ) => ipcRenderer . send ( 'cancel-bluetooth-request' ) , bluetoothPairingRequest : ( callback ) => ipcRenderer . on ( 'bluetooth-pairing-request' , ( ) => callback ( ) ) , bluetoothPairingResponse : ( response ) => ipcRenderer . send ( 'bluetooth-pairing-response' , response ) } ) <! DOCTYPE html > < html > < head > < meta charset = " UTF-8 " > < meta http-equiv = " Content-Security-Policy " content = " default-src 'self'; script-src 'self' " > < title > Web Bluetooth API </ title > </ head > < body > < h1 > Web Bluetooth API </ h1 > < button id = " clickme " > Test Bluetooth </ button > < button id = " cancel " > Cancel Bluetooth Request </ button > < p > Currently selected bluetooth device: < strong id = " device-name " > </ strong > </ p > < script src = " ./renderer.js " > </ script > </ body > </ html > async function testIt ( ) { const device = await navigator . bluetooth . requestDevice ( { acceptAllDevices : true } ) document . getElementById ( 'device-name' ) . innerHTML = device . name || ` ID: ${ device . id } ` } document . getElementById ( 'clickme' ) . addEventListener ( 'click' , testIt ) function cancelRequest ( ) { window . electronAPI . cancelBluetoothRequest ( ) } document . getElementById ( 'cancel' ) . addEventListener ( 'click' , cancelRequest ) window . electronAPI . bluetoothPairingRequest ( ( event , details ) => { const response = { } switch ( details . pairingKind ) { case 'confirm' : { response . confirmed = window . confirm ( ` Do you want to connect to device ${ details . deviceId } ? ` ) break } case 'confirmPin' : { response . confirmed = window . confirm ( ` Does the pin ${ details . pin } match the pin displayed on device ${ details . deviceId } ? ` ) break } case 'providePin' : { const pin = window . prompt ( ` Please provide a pin for ${ details . deviceId } . ` ) if ( pin ) { response . pin = pin response . confirmed = true } else { response . confirmed = false } } } window . electronAPI . bluetoothPairingResponse ( response ) } ) WebHID API ​ The WebHID API can be used to access HID devices such as keyboards and gamepads. Electron provides several APIs for working with the WebHID API: * The select-hid-device event on the Session can be used to select a HID device when a call to navigator.hid.requestDevice is made. Additionally the hid-device-added and hid-device-removed events on the Session can be used to handle devices being plugged in or unplugged when handling the select-hid-device event. Note: These events only fire until the callback from select-hid-device is called. They are not intended to be used as a generic hid device listener. * ses.setDevicePermissionHandler(handler) can be used to provide default permissioning to devices without first calling for permission to devices via navigator.hid.requestDevice . Additionally, the default behavior of Electron is to store granted device permission through the lifetime of the corresponding WebContents. If longer term storage is needed, a developer can store granted device permissions (eg when handling the select-hid-device event) and then read from that storage with setDevicePermissionHandler . * ses.setPermissionCheckHandler(handler) can be used to disable HID access for specific origins. Blocklist ​ By default Electron employs the same blocklist used by Chromium. If you wish to override this behavior, you can do so by setting the disable-hid-blocklist flag: app . commandLine . appendSwitch ( 'disable-hid-blocklist' ) Пример ​ This example demonstrates an Electron application that automatically selects HID devices through ses.setDevicePermissionHandler(handler) and through select-hid-device event on the Session when the Test WebHID button is clicked. docs/fiddles/features/web-hid ( 43.4.0 ) Open in Fiddle * main.js * index.html * renderer.js const { app , BrowserWindow } = require ( 'electron/main' ) function createWindow ( ) { const mainWindow = new BrowserWindow ( { width : 800 , height : 600 } ) mainWindow . webContents . session . on ( 'select-hid-device' , ( event , details , callback ) => { // Add events to handle devices being added or removed before the callback on // `select-hid-device` is called. mainWindow . webContents . session . on ( 'hid-device-added' , ( event , device ) => { console . log ( 'hid-device-added FIRED WITH' , device ) // Optionally update details.deviceList } ) mainWindow . webContents . session . on ( 'hid-device-removed' , ( event , device ) => { console . log ( 'hid-device-removed FIRED WITH' , device ) // Optionally update details.deviceList } ) event . preventDefault ( ) if ( details . deviceList && details . deviceList . length > 0 ) { callback ( details . deviceList [ 0 ] . deviceId ) } } ) mainWindow . webContents . session . setPermissionCheckHandler ( ( webContents , permission , requestingOrigin , details ) => { if ( permission === 'hid' && details . securityOrigin === 'file:///' ) { return true } } ) mainWindow . webContents . session . setDevicePermissionHandler ( ( details ) => { if ( details . deviceType === 'hid' && details . origin === 'file://' ) { return true } } ) mainWindow . loadFile ( 'index.html' ) } app . whenReady ( ) . then ( ( ) => { createWindow ( ) app . on ( 'activate' , function ( ) { if ( BrowserWindow . getAllWindows ( ) . length === 0 ) createWindow ( ) } ) } ) app . on ( 'window-all-closed' , function ( ) { if ( process . platform !== 'darwin' ) app . quit ( ) } ) <! DOCTYPE html > < html > < head > < meta charset = " UTF-8 " > < meta http-equiv = " Content-Security-Policy " content = " default-src 'self'; script-src 'self' " > < title > WebHID API </ title > </ head > < body > < h1 > WebHID API </ h1 > < button id = " clickme " > Test WebHID </ button > < h3 > HID devices automatically granted access via < i > setDevicePermissionHandler </ i > </ h3 > < div id = " granted-devices " > </ div > < h3 > HID devices automatically granted access via < i > select-hid-device </ i > </ h3 > < div id = " granted-devices2 " > </ div > < script src = " ./renderer.js " > </ script > </ body > </ html > function formatDevices ( devices ) { return devices . map ( device => device . productName ) . join ( '<hr>' ) } async function testIt ( ) { document . getElementById ( 'granted-devices' ) . innerHTML = formatDevices ( await navigator . hid . getDevices ( ) ) document . getElementById ( 'granted-devices2' ) . innerHTML = formatDevices ( await navigator . hid . requestDevice ( { filters : [ ] } ) ) } document . getElementById ( 'clickme' ) . addEventListener ( 'click' , testIt ) Web Serial API ​ The Web Serial API can be used to access serial devices that are connected via serial port, USB, or Bluetooth. In order to use this API in Electron, developers will need to handle the select-serial-port event on the Session associated with the serial port request. There are several additional APIs for working with the Web Serial API: * The serial-port-added and serial-port-removed events on the Session can be used to handle devices being plugged in or unplugged when handling the select-serial-port event. Note: These events only fire until the callback from select-serial-port is called. They are not intended to be used as a generic serial port listener. * ses.setDevicePermissionHandler(handler) can be used to provide default permissioning to devices without first calling for permission to devices via navigator.serial.requestPort . Additionally, the default behavior of Electron is to store granted device permission through the lifetime of the corresponding WebContents. If longer term storage is needed, a developer can store granted device permissions (eg when handling the select-serial-port event) and then read from that storage with setDevicePermissionHandler . * ses.setPermissionCheckHandler(handler) can be used to disable serial access for specific origins. Blocklist ​ By default Electron employs the same blocklist used by Chromium. If you wish to override this behavior, you can do so by setting the disable-serial-blocklist flag: app . commandLine . appendSwitch ( 'disable-serial-blocklist' ) Пример ​ This example demonstrates an Electron application that automatically selects serial devices through ses.setDevicePermissionHandler(handler) as well as demonstrating selecting the first available Arduino Uno serial device (if connected) through select-serial-port event on the Session when the Test Web Serial button is clicked. docs/fiddles/features/web-serial ( 43.4.0 ) Open in Fiddle * main.js * index.html * renderer.js const { app , BrowserWindow } = require ( 'electron/main' ) function createWindow ( ) { const mainWindow = new BrowserWindow ( { width : 800 , height : 600 } ) mainWindow . webContents . session . on ( 'select-serial-port' , ( event , portList , webContents , callback ) => { // Add listeners to handle ports being added or removed before the callback for `select-serial-port` // is called. mainWindow . webContents . session . on ( 'serial-port-added' , ( event , port ) => { console . log ( 'serial-port-added FIRED WITH' , port ) // Optionally update portList to add the new port } ) mainWindow . webContents . session . on ( 'serial-port-removed' , ( event , port ) => { console . log ( 'serial-port-removed FIRED WITH' , port ) // Optionally update portList to remove the port } ) event . preventDefault ( ) if ( portList && portList . length > 0 ) { callback ( portList [ 0 ] . portId ) } else { // eslint-disable-next-line n/no-callback-literal callback ( '' ) // Could not find any matching devices } } ) mainWindow . webContents . session . setPermissionCheckHandler ( ( webContents , permission , requestingOrigin , details ) => { if ( permission === 'serial' && details . securityOrigin === 'file:///' ) { return true } return false } ) mainWindow . webContents . session . setDevicePermissionHandler ( ( details ) => { if ( details . deviceType === 'serial' && details . origin === 'file://' ) { return true } return false } ) mainWindow . loadFile ( 'index.html' ) mainWindow . webContents . openDevTools ( ) } app . whenReady ( ) . then ( ( ) => { createWindow ( ) app . on ( 'activate' , function ( ) { if ( BrowserWindow . getAllWindows ( ) . length === 0 ) createWindow ( ) } ) } ) app . on ( 'window-all-closed' , function ( ) { if ( process . platform !== 'darwin' ) app . quit ( ) } ) <! DOCTYPE html > < html > < head > < meta charset = " UTF-8 " > < meta http-equiv = " Content-Security-Policy " content = " default-src 'self'; script-src 'self' " > < title > Web Serial API </ title > < body > < h1 > Web Serial API </ h1 > < button id = " clickme " > Test Web Serial API </ button > < p > Matching Arduino Uno device: < strong id = " device-name " " > </ strong > </ p > < script src = " ./renderer.js " > </ script > </ body > </ html > async function testIt ( ) { const filters = [ { usbVendorId : 0x2341 , usbProductId : 0x0043 } , { usbVendorId : 0x2341 , usbProductId : 0x0001 } ] try { const port = await navigator . serial . requestPort ( { filters } ) const portInfo = port . getInfo ( ) document . getElementById ( 'device-name' ) . innerHTML = ` vendorId: ${ portInfo . usbVendorId } | productId: ${ portInfo . usbProductId } ` } catch ( ex ) { if ( ex . name === 'NotFoundError' ) { document . getElementById ( 'device-name' ) . innerHTML = 'Device NOT found' } else { document . getElementById ( 'device-name' ) . innerHTML = ex } } } document . getElementById ( 'clickme' ) . addEventListener ( 'click' , testIt ) WebUSB API ​ The WebUSB API can be used to access USB devices. Electron provides several APIs for working with the WebUSB API: * The select-usb-device event on the Session can be used to select a USB device when a call to navigator.usb.requestDevice is made. Additionally the usb-device-added and usb-device-removed events on the Session can be used to handle devices being plugged in or unplugged when handling the select-usb-device event. Note: These two events only fire until the callback from select-usb-device is called. They are not intended to be used as a generic usb device listener. * The usb-device-revoked event on the Session can be used to respond when device.forget() is called on a USB device. * ses.setDevicePermissionHandler(handler) can be used to provide default permissioning to devices without first calling for permission to devices via navigator.usb.requestDevice . Additionally, the default behavior of Electron is to store granted device permission through the lifetime of the corresponding WebContents. If longer term storage is needed, a developer can store granted device permissions (eg when handling the select-usb-device event) and then read from that storage with setDevicePermissionHandler . * ses.setPermissionCheckHandler(handler) can be used to disable USB access for specific origins. * `ses.setUSBProtectedClassesHandler can be used to allow usage of protected USB classes that are not available by default. Blocklist ​ By default Electron employs the same blocklist used by Chromium. If you wish to override this behavior, you can do so by setting the disable-usb-blocklist flag: app . commandLine . appendSwitch ( 'disable-usb-blocklist' ) Пример ​ This example demonstrates an Electron application that automatically selects USB devices (if they are attached) through ses.setDevicePermissionHandler(handler) and through select-usb-device event on the Session when the Test WebUSB button is clicked. docs/fiddles/features/web-usb ( 43.4.0 ) Open in Fiddle * main.js * index.html * renderer.js const { app , BrowserWindow } = require ( 'electron/main' ) function createWindow ( ) { const mainWindow = new BrowserWindow ( { width : 800

Links found on this page

  1. Перейти к основному содержанию [direct]
  2. Electron [direct]
  3. Документация [direct]
  4. API [direct]
  5. Блог [direct]
  6. Electron Forge [direct]
  7. Electron Fiddle [direct]
  8. Управление [direct]
  9. Примеры [direct]
  10. Ресурсы [direct]
  11. Релизы [direct]
  12. English [direct]
  13. Deutsch [direct]
  14. Español [direct]
  15. Français [direct]
  16. 日本語 [direct]
  17. Português [direct]
  18. 中文 [direct]
  19. Процессы в Electron [direct]
  20. Рекомендации [direct]
  21. Примеры [direct]
  22. Темный режим [direct]
  23. In-App Purchases [direct]
  24. Горячие клавиши [direct]
  25. Deep Links [direct]
  26. Desktop Launcher Actions [direct]
  27. Menus [direct]
  28. Многопоточность [direct]
  29. Нативное перемещение файла [direct]
  30. История навигации [direct]
  31. Notification (Оповещения) [direct]
  32. Закадровый рендеринг [direct]
  33. Обнаружение Online/Offline событий [direct]
  34. Progress Bars [direct]
  35. Недавние документы [direct]
  36. Representing Files in a BrowserWindow [direct]
  37. SpellChecker [direct]
  38. Web Embeds [direct]
  39. Taskbar Customization [direct]
  40. Window Customization [direct]
  41. Разработка [direct]
  42. Native Node Modules [direct]
  43. Распространение [direct]
  44. Тестирование и отладка [direct]
  45. Ссылки [direct]
  46. Вклад [direct]
  47. Web Bluetooth API [direct]
  48. select-bluetooth-device event on the webContents [direct]
  49. ses.setBluetoothPairingHandler(handler) [direct]
  50. docs/fiddles/features/web-bluetooth ( 43.4.0 ) [direct]
  51. Open in Fiddle [direct]
  52. WebHID API [direct]
  53. blocklist [direct]
  54. docs/fiddles/features/web-hid ( 43.4.0 ) [direct]
  55. Open in Fiddle [direct]
  56. Web Serial API [direct]
  57. blocklist [direct]
  58. docs/fiddles/features/web-serial ( 43.4.0 ) [direct]
  59. Open in Fiddle [direct]
  60. WebUSB API [direct]
  61. device.forget() [direct]
  62. protected USB classes [direct]
  63. docs/fiddles/features/web-usb ( 43.4.0 ) [direct]
  64. Open in Fiddle [direct]
  65. Редактировать эту страницу [direct]
  66. Безопасность [direct]
  67. Discord [direct]
  68. Bluesky [direct]
  69. X [direct]
  70. Mastodon [direct]
  71. Stack Overflow [direct]
  72. GitHub [direct]
  73. Open Collective [direct]
  74. Панель управления инфраструктурой [direct]
  75. OpenJS Foundation [direct]
  76. Политике в отношении товарных знаков [direct]
  77. Списке товарных знаков [direct]
  78. Условия использования [direct]
  79. Политика конфиденциальности [direct]
  80. Устав [direct]