跳转到主内容

设备访问

类似基于 Chromium 的浏览器一样, Electron 也提供了通过 web API 访问设备硬件的方法。 大部分接口就像在浏览器调用的 API 一样,但有一些差异需要考虑到。 Electron和浏览器之间的主要区别是请求访问设备时发生的情况。 在浏览器中,用户可以在弹出窗口中允许访问单独的设备。 在 Electron API中,提供了可供开发者自动选择设备或提示用户通过开发者创建的接口选择设备。

Web Bluetooth API

Web Bluetooth API 可以被用来连接蓝牙设备。 为了在 Electron 中使用此 API ,开发者将需要处理与设备请求相关的webContent的select-bluetooth-device事件

此外,当需要进行例如pin的额外验证时,ses.setBluetoothPairingHandler(handler)可以被用来在Windows或Linux上处理配对蓝牙设备。

示例

这个示例演示了一个 Electron 应用程序,当点击了 Test Bluetooth 按钮时,它会自动选择第一个可用的蓝牙设备。

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()
})

WebHID API

WebHID API 可以用于访问HID 设备,例如 键盘和游戏机。 Electron 提供了几个使用 WebHID API的接口:

  • navigator.hid.requestDevice被调用时,Session的select-hid-device事件可以用来选择一个HID设备。 此外,在处理select-hid-device事件时,Session的hid-device-addedhid-device-removed事件可以用来处理设备拔插。 注意: 这些事件仅会在 select-hid-device 的回调之后被触发。 它们不能作为通用HID设备监听器使用。
  • 在第一次调用 navigator.hid.requestDevice 前, 可以通过 ses.setDevicePermissionHandler(handler) 给予设备默认权限, 此外,Electron的默认行为是在相应的WebContents的生命周期内存储已授予的设备权限。 如果需要更长期的存储,开发人员可以存储设备许可信息(比如: 在处理 select-hid-device 事件时), 然后通过 setDevicePermissionHandler 从存储的信息中读取
  • ses.setPermissionCheckHandler(handler)可以用来禁用特定源的HID访问。

阻止列表

默认情况下,Electron 使用与 Chromium 相同的 blocklist 如果您想要覆盖此行为,您可以通过设置 disable-hid-blocklist 标志来做到这一点:

app.commandLine.appendSwitch('disable-hid-blocklist')

示例

这个例子演示了,一个Electron应用在Test WebHID按钮被点击时,自动通过ses.setDevicePermissionHandler(handler)Session的select-hid-device事件选择HID设备。

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()
})

Web Serial API

Web Serial API 可以被用来访问串口设备比如 USB 或蓝牙。 为了在Eletron中使用这个API,开发者需要处理与串口请求相关的Session的select-serial-port事件

有几个额外的 API 用于与 Web Serial API 合作:

  • 在处理select-serial-port事件时,Session的serial-port-addedserial-port-removed事件可以用来处理设备拔插。 注意: 这些事件仅会在 select-serial-port 的回调之后被触发。 它们不能作为通用串口监听器使用。
  • 在第一次调用 navigator.serial.requestPort 前, 可以通过 ses.setDevicePermissionHandler(handler) 给予设备默认权限, 此外,Electron的默认行为是在相应的WebContents的生命周期内存储已授予的设备权限。 如果需要更长期的存储,开发人员可以存储设备许可信息(比如: 在处理 select-serial-port 事件时), 然后通过 setDevicePermissionHandler 从存储的信息中读取
  • ses.setPermissionCheckHandler(handler)可以用来禁用特定源的串口访问。

示例

这个例子演示了一个Eletron应用通过ses.setDevicePermissionHandler(handler)自动选择窗口设备,以及当Test Web Serial按钮被点击时通过Session的select-serial-port事件选择第一个可用的Arduino Uno串口设备(如果已连接)。

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()
})

WebUSB API

WebUSB API 可用于访问USB设备。 Electron提供了几个与WebUSB API配合使用的API:

示例

这个例子演示了,一个Electron应用在Test WebUSB按钮被点击时,自动通过ses.setDevicePermissionHandler(handler)Session的select-usb-device事件选择USB设备(如果它们已被连接)。

const { app, BrowserWindow } = require('electron/main')

function createWindow () {
const mainWindow = new BrowserWindow({
width: 800,
height: 600
})

let grantedDeviceThroughPermHandler

mainWindow.webContents.session.on('select-usb-device', (event, details, callback) => {
// Add events to handle devices being added or removed before the callback on
// `select-usb-device` is called.
mainWindow.webContents.session.on('usb-device-added', (event, device) => {
console.log('usb-device-added FIRED WITH', device)
// Optionally update details.deviceList
})

mainWindow.webContents.session.on('usb-device-removed', (event, device) => {
console.log('usb-device-removed FIRED WITH', device)
// Optionally update details.deviceList
})

event.preventDefault()
if (details.deviceList && details.deviceList.length > 0) {
const deviceToReturn = details.deviceList.find((device) => {
return !grantedDeviceThroughPermHandler || (device.deviceId !== grantedDeviceThroughPermHandler.deviceId)
})
if (deviceToReturn) {
callback(deviceToReturn.deviceId)
} else {
callback()
}
}
})

mainWindow.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
if (permission === 'usb' && details.securityOrigin === 'file:///') {
return true
}
})

mainWindow.webContents.session.setDevicePermissionHandler((details) => {
if (details.deviceType === 'usb' && details.origin === 'file://') {
if (!grantedDeviceThroughPermHandler) {
grantedDeviceThroughPermHandler = details.device
return true
} else {
return false
}
}
})

mainWindow.webContents.session.setUSBProtectedClassesHandler((details) => {
return details.protectedClasses.filter((usbClass) => {
// Exclude classes except for audio classes
return usbClass.indexOf('audio') === -1
})
})

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()
})