Search code examples
angulartypescriptgoogle-chrome-devtoolsweb-bluetooth

navigator.bluetooth not working in typescript


I am trying to make the chrome bluetooth API call and I am not getting success via typescript. I've already tried applying a file in html () but also to no avail. But if you copy the code and paste it into the browser console, the code runs perfectly :(

Error in console (If run code in Ts):

DOMException: Must be handling a user gesture to show a permission request.

// Typescript/TS:

requestBluetooth() {
    (window.navigator as any).bluetooth.requestDevice({ filters: [{ services: [this.PRINT_SERVICE_CODE] }] })
      .then(device => {
        return device.gatt.connect();
      })
      .then(server => {
        return server.getPrimaryService(this.PRINT_SERVICE_CODE);
      })
      .then(service => {
        return service.getCharacteristic('00002af1-0000-1000-8000-00805f9b34fb');
      })
      .then((characteristic) => {
        this.sendTextData(characteristic);
      })
      .catch(error => console.log(error));
  }

sendTextData(characteristic) {
    // Get the bytes for the text
    const encoder = new TextEncoder('UTF-8');
    const text = encoder.encode('TESTETSETS' + '\u000A\u000D');
    return characteristic.writeValue(text)
      .then(() => console.log('Write done.'));
  }

// Working in Console Browser:

const PRINT_SERVICE_CODE = '000018f0-0000-1000-8000-00805f9b34fb';

const sendTextData = (function (characteristic) {
  const encoder = new TextEncoder('UTF-8');
  const text = encoder.encode('TESTETSETS' + '\u000A\u000D');
  return characteristic.writeValue(text)
    .then(() => console.log('Write done.'));
})

const request = (function () {
  navigator.bluetooth.requestDevice({ filters: [{ services: [PRINT_SERVICE_CODE] }] })
  .then(device => {
    return device.gatt.connect();
  })
  .then(server => {
    return server.getPrimaryService(PRINT_SERVICE_CODE);
  })
  .then(service => {
    return service.getCharacteristic('00002af1-0000-1000-8000-00805f9b34fb');
  })
  .then((characteristic) => {
    this.sendTextData(characteristic);
  })
  .catch(error => console.log(error));
})

request();

// Informations of Project:

Angular CLI: 6.0.8

Node: 8.11.3

OS: linux x64

Angular: 6.0.9


Solution

  • Is requestBluetooth() being called in the event handler for a user gesture (such as a button click)? I can't find it at the moment but I recall a similar question related to Angular where some kinds of click handlers were not retaining the user gesture token.