Encountering the "RequestDevice() chooser has been cancelled by the user" error when using Electron 17.x with Web Bluetooth

After reviewing the following StackOverflow resources:

  1. Web Bluetooth & Chrome Extension: User cancelled the requestDevice() chooser
  2. Electron Web Bluetooth API requestDevice() Error
  3. Can you manipulate web bluetooth chooser that shows after calling requestDevice()?

However, the solutions provided in these sources do not seem to be effective.

Here is my main file:

import { app, BrowserWindow } from "electron";

/**
 * Reference: https://www.electronjs.org/docs/tutorial/quick-start#create-the-main-script-file
 */
async function createWindow(): Promise<BrowserWindow> {
  // Creating a browser window
  const win = new BrowserWindow({
    webPreferences: {
      nodeIntegration: true,
    },
  });

  /**
   * Handle bluetooth connection
   * Reference: https://www.electronjs.org/docs/latest/tutorial/devices#web-bluetooth-api
   */
  win.webContents.on("select-bluetooth-device", (event, devices, callback) => {
    event.preventDefault();
    if (devices.length > 0) {
      callback(devices[0].deviceId);
    }
  });

  // Load index.html
  win.maximize();
  await win.loadFile("./dist/renderer/index.html");
  return win;
}

function setUpElectronApp(): void {
  // Browser window
  let win: BrowserWindow | undefined;

  // Enable webBluetooth
  app.commandLine.appendSwitch("enable-experimental-web-platform-features", "true");
  app.commandLine.appendSwitch("enable-web-bluetooth", "true");

  // Create bowser window once the electron app is initialized
  app
    .whenReady()
    .then(() => {
      createWindow()
        .then((response) => {
          win = response;
          console.log(win);
        })
        .catch((err) => {
          throw err as Error;
        });
    })
    .catch((err) => {
      throw err as Error;
    });

  // Quit the application when it no longer has any open windows
  app.on("window-all-closed", () => {
    if (process.platform !== "darwin") {
      app.quit();
      win = undefined;
    }
  });

  // Create a new browser window only when the application has no visible windows being activated
  app.on("activate", () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
        .then((response) => {
          win = response;
          console.log(win);
        })
        .catch((err) => {
          throw err;
        });
    }
  });
}

setUpElectronApp();

And here is some code from the renderer file:

function onDisconnected(event: Event) {
  const device = event.target as BluetoothDevice;
  console.log(`Device ${device.name} is disconnected.`);
}

export async function deviceConnect(): Promise<{ heartRate: any, batteryLevel: any, deviceID: string }> {

  const device = await navigator.bluetooth.requestDevice({
    filters: [
      {
        namePrefix: "Polar Sense",
        manufacturerData: [{ companyIdentifier: 0x006b }],
      },
    ],
    acceptAllDevices: false,
    optionalServices: [0x180d, 0x180f],
  });

  device.addEventListener("gattserverdisconnected", onDisconnected);

  const server = await device.gatt?.connect();

  const heartRateService = await server?.getPrimaryService(0x180d);
  const heartRate = await heartRateService?.getCharacteristic(0x2a37);

  const batteryLevelService = await server?.getPrimaryService(0x180f);
  const batteryLevel = await batteryLevelService?.getCharacteristic(0x2a19);

  return { heartRate, batteryLevel, deviceID: device.name };
}

I have a button on my front end that triggers the above function when clicked. Unfortunately, I keep receiving the error message:

Uncaught (in promise) DOMException: User cancelled the requestDevice() chooser.
I have tried different versions of Electron with no success. Any insights would be greatly appreciated.

Please advise if utilizing the Web Bluetooth API in Electron is feasible. I am using "electron": "^17.4.7" on macOS Monterey (12.4).

If you notice any issues or have suggestions regarding the approach outlined above, please share your feedback.

Answer №1

In order to use Bluetooth with Electron and VSCode, I had to grant permissions in System Preferences.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Webpack and typescript are encountering a critical dependency issue where the require function is being utilized in a manner that prevents static extraction of dependencies

Having recently started diving into typescript and webpack programming, I must admit that my background in this area is limited. Despite searching through similar questions on Stack Overflow, none of the solutions provided so far have resolved my issue: I ...

Is there a way to attach a ref to a Box component in material-ui using Typescript and React?

What is the best way to attach a ref to a material-ui Box component in React, while using TypeScript? It's crucial for enabling animation libraries such as GreenSock / GSAP to animate elements. According to material-ui documentation, using the itemRef ...

My component fails to load using Angular Router even though the URL is correct

I have been experiencing an issue while trying to load my Angular component using the router. The component never appears on the screen and there are no error messages displayed. app-routing-module { path: '', redirectTo: '/home', ...

Steps for incorporating a type declaration for an array of objects in a React application with TypeScript

How can I specify the type for an array of objects in React using TypeScript? Here is the code snippet: const SomeComponent = (item: string, children: any) => { //some logic } In this code, you can see that I am currently using 'any' as ...

Discover a more efficient method for expanding multiple interfaces

Hey there, I'm having some trouble with TypeScript and generics. Is there a better way to structure the following code for optimal cleanliness and efficiency? export interface Fruit { colour: string; age: number; edible: boolean; } export inte ...

Tips for incorporating Angular2 into Eclipse using TypeScript

Recently, I delved into the world of Angular 2 and noticed that TypeScript is highly recommended over JavaScript. Intrigued by this recommendation, I decided to make the switch as well. I came across a helpful guide for setting up everything in Eclipse - f ...

transferring attributes from a higher component to a lower one (modal)

I am relatively new to React and I want to share a detailed problem description: I have a Todo project that consists of multiple interfaces. The main interface displays all the lists, each containing a title, a group of tasks, and a button to create a ta ...

What is the process for calculating a class property in typescript?

If I were writing this in JavaScript, it would look like: function a(b,c) {this.foo = b; this.bar = c; this.yep = b+c} // undefined b = new a(1,2) // a {foo: 1, bar: 2, yep: 3} However, I've been struggling to achieve the same in TypeScript. None of ...

Incorporate a New Feature into my NPM Package

I've been searching high and low for an answer to this, but I'm still stuck. I'm working on a module in Angular 2 with ng-module, and everything is functioning properly. However, I'm struggling to assign a property to another property w ...

Display a loading indicator with the shortest possible delay whenever utilizing the React Router v6 Link functionality

Integrate React and Router v6 App.tsx: const Page1 = lazy(() => pMinDelay(import('./views/Page1'), 500)) const Page2 = lazy(() => pMinDelay(import('./views/Page2'), 500)) return ( <Suspense fallback={<Loading/>}gt ...

Tips for creating an API URL request with two search terms using Angular and TypeScript

I have developed a MapQuest API application that includes two input boxes - one for the "from" location and another for the "to" location for navigation. Currently, I have hardcoded the values for these locations in my app.component file, which retrieves t ...

The result of comparing with `instanceof` in TypeScript

class Department { name: string; constructor(n: string) { this.name = n; } describe(this: Department){ console.log('department: ' +this.name); } } const frontend = new Department('frontend'); frontend.describe(); con ...

Encountering issues with accessing a variable before its initialization in the getServerSideProps function in

Currently, I am working on setting up Firebase and configuring the APIs and functions to retrieve necessary data in my firebase.tsx file. Afterwards, I import them into my pages/index.tsx file but I am encountering an issue where I cannot access exports af ...

A pop-up window displaying an electron error message appears, but no errors are logged in the console

In a Nutshell: While developing a single-page website with Electron, I encountered the common issue of jQuery not being globally accessible. To tackle this problem, I decided to simplify it by using a quick start example, but unfortunately, I'm strugg ...

Utilizing interpolation for a CSS class defined in an external file within Angular 2

Is it feasible to send a variable to a CSS class in an external CSS file within Angular 2, such as: import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', sty ...

Issue: "contains method is not supported" in Ionic 2

I'm currently working on a code to validate the contents of my input field, but I've encountered an issue with using the contains function. Here's the TypeScript function I have written: checkFnameFunction(name){ if(name.contains("[a-z ...

Angular: Enable function to await Observable completion before returning result

I require assistance with the user function below: getUser(uuid: string): Observable<WowUserDataModel> { let user: WowUserDataModel = { login: null, userUuid: uuid, firstName: null, lastName: null, displayName: nul ...

Scripts in iframes within webviews are not preloading and executing properly

When using the <webview> tag in the renderer process within the <body> of a web page, the following code is used: <webview src="http://somewebpage.com" preload="somescript.js"> The script somescript.js will be execute ...

Looping through NavItems component using JavaScript or Angular

My Angular project includes a navbar component with an app sidebar that has a navItems attribute. Below is the content of my navBar: <app-header style="background-color : #e65100;" [fixed]="true" [navbarBrandFull]="{ src: &a ...

Changing the Image Source in HTML with the Power of Angular2

Despite my efforts, I'm unable to display the updated image in my HTML file. In my TypeScript file, the imageUrl is updating as expected and I've verified this in the console. However, the HTML file is not reflecting these changes. In my researc ...