Guide to adding eventListener to web-bluetooth API using JavaScript

I am looking to create a compact physical button device that can be used to control the playback of 3 short audio clips on my web app through the web Bluetooth API. Essentially, with each click of the physical button, the next audio clip will play.

According to the information I found in this tutorial, it is recommended to utilize a custom characteristic by providing the complete UUID of the device. However, when trying to set up an event listener to trigger the audio playback function, I encountered an error message saying

Cannot read property 'addEventListener' of undefined
. I'm not sure what's causing this issue.

Could there be something crucial that I have overlooked or misunderstood? Please keep in mind that I have yet to acquire the physical button, so for now, I am testing the Bluetooth connection using my iPhone, hence the test function is only intended to check for any output.

Below is the code snippet:

$("#bluetooth").on("click", function(){
        const controlServiceUUID = '00001805-0000-1000-8000-00805f9b34fb'; // Full UUID
        const commandCharacteristicUUID = '00002a0f-0000-1000-8000-00805f9b34fb'; // [READ]
        const commandCharacteristicUUID2 = '00002a0f-0000-1000-8000-00805f9b34fb'; // [READ, NOTIFY]

        console.log('Searching Bluetooth Device...');

        navigator.bluetooth.requestDevice({
            acceptAllDevices: true,
            optionalServices: [controlServiceUUID]
        })

        .then(device => {
            console.log("Got device name: ", device.name);
            console.log("id: ", device.id);
            return device.gatt.connect();
        })

        .then(server => {
            // Step 3: Get the Service
            serverInstance = server;
            return server.getPrimaryService(controlServiceUUID);
            console.log("Getting PrimaryService");
        })

        .then(service => {
            service.getCharacteristic(commandCharacteristicUUID);
            console.log("Getting Characteristic");
        })

        .then(characteristic => {
            // 0x01,3,0x02,0x03,0x01

            characteristic.addEventListener('characteristicvaluechanged', test);             
        })

        .catch(function(error) {
            console.log("Something went wrong. " + error);
        });

       function test(event) {
           let commandValue = event.target.value.getUint8(0);
           console.log("Hello");
       }
   });

Answer №1

In order to utilize the feature, it is essential to return the Promise. Please refer to the instructions provided below.


        .then(service => {
            console.log("Acquiring Characteristic");
            return service.getCharacteristic(commandCharacteristicUUID);
        })

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

communication link between smartphone and computer

I am looking to create a connection between a mobile device and computer for interactive communication. I want the ability to send and receive data on both ends, similar to a chat client. Can you provide guidance on how to achieve this? I am considering ...

Tips for concealing the final click (add) tab after it has been clicked and revealing the hidden (add) button when the user clicks on the remove button

I have created a form where users can add tests. Everything is working smoothly but I want the previous "Add Another Test" field to be removed when the user clicks on it and a new field to be shown. Everything is running well, but the issue is that when t ...

Troubleshooting a Node.js problem related to a schema error involving user ID validation

I am new to working with node.js express and I am facing an issue with my registration form. I have implemented a condition to check if the user ID is already in the database, but for some reason, it always shows a validation error message regardless of th ...

The result callback for registering geofences is not activated within an AsyncTask

Currently, I have a background job running to re-register Geofences after they expire. The code is triggered successfully, and the notification is being fired in the onPostExecute method. However, the code inside the setResultCallback function is not bein ...

How to use Nativescript to retain the keyboard visibility on Android when pressing the Enter key

When attempting to create a chat view in Nativescript Javascript, I encountered an issue. After pressing the "Send" button on the keyboard, the message is sent; however, there is a strange behavior where the first 'enter' press on the keyboard is ...

Unable to change the color of InputBase component's placeholder in React.js

I've been attempting to modify the color of the placeholder in an inputbase. I came across several methods online and tried implementing them, but none have been successful. Below are the codes I have tried. <InputBase id="input-id&quo ...

I encounter obstacles when trying to execute various tasks through npm, such as downloading packages

Currently, I am facing an issue while trying to set up backend development using node.js on my personal computer. The problem lies with the npm command as it is not functioning correctly. Despite successfully installing a file without any errors, I am unab ...

Retrieving the selected value in Vue.js

Hey there! I'm currently working on retrieving the selected value of a select element. Below is the HTML code for the select: <select id="employee"> <option v-bind:key="employee" v-for="employee of employees" ...

Is it possible to add or remove a class at the top of a div

Is there a way to create a fading effect for a class based on when a specific div enters the window? I am looking to implement this functionality, how can I achieve this? $(window).scroll(function() { var registerTop = $('.register').offset ...

Creating a dynamic sidebar based on roles in AngularJS

I'm looking to create a dynamic sidebar based on the user's role, which is stored in $rootScope.login. However, I'm unsure of how to integrate it into template.js. Below is my JavaScript code and I'm still relatively new to AngularJS. ...

Request for removal in Express.js

Currently in the process of developing a MERN-stack app, but encountering issues with the delete request function. Here is the relevant code snippet: Upon attempting to send a delete request via Postman, an error message is displayed. I have researched ...

Guide to creating an animated filter effect for a list with the useTransition feature in react-spring

Currently, I am working on animating the transition of a list when it is filtered using the latest useTransition hook changes in version 9.x of react-spring. My goal is to make the remaining items smoothly move to their new positions as the list items are ...

Fixed position toolbar within a container positioned beside a dynamically sized sidebar navigation

I'm trying to figure out how to create a fixed toolbar that fills the remaining width of the page when a side nav is collapsible. Setting the width to 100% causes it to overflow the page due to the dynamic nature of the side nav. Using calc() isn&apos ...

Retrieve a value from a different collection in MongoDb

Is it possible to copy certain fields from one collection to another? I am looking to copy the values of 'bar' to the 'foo' collection, excluding the 'type' field. Additionally, I want to add a new _id and an extra field (use ...

Display the component only if the image source is legitimate

Before rendering an Image component, I want to ensure that the URL is valid and not broken. My current approach seems error-free and the onload function is functioning properly. However, I suspect there might be an issue with how I am handling the return ...

Incorporating a JSON file through a script element

A customized I18n plugin has been developed to accept various languages through json files. The goal is to simplify usage for users by allowing them to easily insert their json package directly into a page along with the script: <script id="pop-languag ...

Send input data to a script seamlessly without triggering a page reload

I'm facing an issue with sending form values to a script. My goal is to have the form values displayed on another part of the page when the user clicks a button. While I can achieve this using PHP or similar web scripting languages by sending the valu ...

Having issues with AngularJS rzslider failing to dispatch updated slider value

Hello, I am currently using the rzmodule/rzslider in AngularJS. However, after changing the slider to a specific range, the ng-modal is not returning the updated value. It keeps returning the initial value of 10000 that was configured initially. $scope.sl ...

The compilation process for react-native-interactable failed due to the task ':react-native-interactable:compileDebugJavaWithJavac'

My current challenge involves running my app on an Android device. I have already installed all the necessary dependencies and I am working on a Windows platform. Here are the steps I have taken: Upon entering the command react-native run-android, I enco ...

JavaScript file does not execute onload function

Whenever I try to execute the window.onload function from my .js file, it seems to not be firing as expected. <script type="text/javascript" src="{% static 'jsfile.js' %}"></script> window.onload = function() { alert(' ...