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.

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

Changing the type of value in a React select onChange

<Select options={options} value={selectedBusinessList} isMulti placeholder="Select Business" onChange={(value: any) => setSelectedBusinessList(value)} onInputChange={query => { if ...

Confirm that a specific value exists within an enumerated set

I am currently using Angular 13.3.9 and typescript 4.6.4. My main objective is to determine if a value is referencing an enum. Below is the code snippet: export enum HttpFunctionalErrorCodes { ACCOUNT_NOT_FOUND = 'ACCOUNT_NOT_FOUND', USER_ ...

Typescript: searching for a specific type within an array of objects

The title may be a bit unclear, but I'm struggling to find a better way to explain it. I have a predefined set of classes from a third-party library that I cannot modify. The specific content of these classes is not relevant, as it's just for i ...

Arrange a JavaScript map based on its values and ensure that a specific field index remains at the top position

I'm sure this question may seem simple to some, but as a JavaScript novice, I couldn't find the answer myself. Here is the code snippet I'm working with: Let map = new Map<String,String> map.set('0', select) map.set('1&a ...

A guide on incorporating JavaScript variables within a GraphQL-tag mutation

I'm having trouble consistently using javascript variables inside graphql-tag queries and mutations when setting up an apollo server. Here's a specific issue I've encountered: gql` mutation SetDeviceFirebaseToken { SetDeviceFirebaseTok ...

Tips on sorting a FileList object selected by a directory picker in JavaScript/TypeScript

I need to filter or eliminate certain files from a FileList object that I obtained from a directory chooser. <input type="file" accept="image/*" webkitdirectory directory multiple> Within my .ts file: public fileChangeListener($event: any) { let ...

Error: The payload in action is not able to be iterated over

Currently, I am delving into the world of ngrx, but I seem to have hit a roadblock. I'm encountering an issue that I can't seem to fix on my own. If anyone out there has some insight and expertise to offer, please help me out. I keep running into ...

In fact, retrieve the file from an S3 bucket and save it to your local

I've been attempting to retrieve an s3 file from my bucket using this function: async Export() { const myKey = '...key...' const mySecret = '...secret...' AWS.config.update( { accessKeyId: myKey, secretAcces ...

The user's type from express-session is not being properly detected by Typescript

I have a process where I retrieve the user object from the database and set it on the express-session: export const postLogin = async ( request: Request, response: Response, next: NextFunction ): Promise<void> => { try { re ...

Trigger the Material UI DatePicker to open upon clicking the input field

I have a component that is not receiving the onClick event. I understand that I need to pass a prop with open as a boolean value, but I'm struggling to find a way to trigger it when clicking on MuiDatePicker. Here is an image to show where I want to ...

What is the reason for not requiring checks with Union Types when utilizing a variable, yet necessitating them within a function?

Currently working on some Typescript challenges and encountered a scenario involving a union type. In this example, the function getIstanbulPostalCode is declared to return either a string or a number: function getIstanbulPostalCode(): string | number { ...

Iterate through an array containing objects that may have optional properties, ensuring to loop through the entire

I need help iterating through an array of objects with a specific interface structure: export interface Incident { ID: string; userName1?: string; userName2?: string; userPhoneNumber?: string; crashSeverity: number; crashTime: number; } Here ...

Generating automatic generic types in Typescript without needing to explicitly declare the type

In the scenario where I have an interface containing two functions - one that returns a value, and another that uses the type of that value in the same interface - generics were initially used. However, every time a new object was created, the type had to ...

Attempting to execute a post request followed by a get request

I need assistance optimizing my code. What I am trying to achieve is to create a user (partner) and upon completion of the post request, fetch all partners from an API. This includes the newly created partner so that I can access their ID to use in subsequ ...

Next.js API routes encountering 404 error

I am encountering an issue with calling my route API (404) in my new nextjs project. The route API can be found at src/app/api/speed.js Within my page src/app/page.tsx, I have the following code snippet: fetch("api/speed").then(res=>res.json ...

Issue with handsontable numbro library occurs exclusively in the production build

Encountering an error while attempting to add a row to my handsontable instance: core.js.pre-build-optimizer.js:15724 ERROR RangeError: toFixed() digits argument must be between 0 and 100 at Number.toFixed () at h (numbro.min.js.pre-build-op ...

What is the best way to parse a JSON file and create a dynamic webpage using jQuery with the data from the

As someone who is new to working with Node.js and JSON, I am encountering some issues when trying to extract data from a JSON file. Below is the code that I have written: 'use strict'; const fs = require('fs'); let questsRawData = fs ...

How come TypeScript tuples support the array.push method?

In the TypeScript code snippet below, I have specified the role to be of Tuple type, meaning only 2 values of a specified type should be allowed in the role array. Despite this, I am still able to push a new item into the array. Why is the TS compiler not ...

Guide to sending jQuery data back to main class in TypeScript

Hi everyone, I'm diving into the world of typescript and JQuery. I have a simple question. In my typescript class called DatePicker, I am calling a function. Here's a snippet of the code: Class DatePicker { private pickerData; public update( ...

Encountering an error while compiling the Angular 8 app: "expected ':' but got error TS1005"

As I work on developing an Angular 8 application through a tutorial, I find myself facing a challenge in my header component. Specifically, I am looking to display the email address of the currently logged-in user within this component. The code snippet fr ...