按照Electron官网的示例,去连接蓝牙
https://www.electronjs.org/docs/latest/tutorial/devices#web-bluetooth-api
如果想要开启软件,就连接蓝牙,会报错:
Uncaught (in promise) DOMException: Failed to execute 'requestDevice' on 'Bluetooth': Must be handling a user gesture to show a permission request.
可以使用如下方法,去模拟用点击操作,以绕过Chrome的安全限制:
mainWindow.webContents.executeJavaScript(document.getElementById("clickme").click();
,true );
修改后的main.js如下:
const { app, BrowserWindow, ipcMain } = require('electron')
const path = require('path')
app.commandLine.appendSwitch('enable-features', 'ElectronSerialChooser')
let bluetoothPinCallback
let selectBluetoothCallback
function createWindow () {
const mainWindow = new BrowserWindow({
width: 1600,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
mainWindow.webContents.openDevTools();
mainWindow.webContents.on('select-bluetooth-device', (event, deviceList, callback) => {
event.preventDefault()
selectBluetoothCallback = callback
const result = deviceList.find((device) => {
console.log("======>" + device.deviceName)
return device.deviceName === 'Phoenix Neo 2'
})
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) => {
console.log("bluetooth-pairing-response")
bluetoothPinCallback(response)
})
mainWindow.webContents.session.setBluetoothPairingHandler((details, callback) => {
console.log("bluetooth-pairing-request")
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')
mainWindow.webContents
.executeJavaScript(`document.getElementById("clickme").click();`,true );
}
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()
})
function handleIPC(win) {
win.webContents.send('do-some-render-work');
}