Obtain Blob using Uint8Array in JavaScript

Hello, I am currently facing an issue while trying to retrieve data from a WebSocket using JS and VUE. Here's the problem I'm encountering:

In order to receive data, I am utilizing the following code snippet:

created() {
console.log('Starting Connection to WebSocket')
this.connection = new WebSocket('ws://127.0.0.1:8080/live')
// this.connection = new WebSocket('ws://echo.websocket.org')
this.onopen = function (event) {
  console.log(event)
  console.log('Success')
}
this.onmessage = webSocketOnMSG
 },

Furthermore, I am attempting to parse a blob of data:

 function webSocketOnMSG(msg) {
  if (typeof (msg.data) === 'string') {
    jsonMSG(msg.data)
    return
  }
  bytes = new Uint8Array(msg.data)
  console.log('!!!BYTE', bytes)
  type = bytes[0]
  switch (type) {

  }
}

When console.log('!!!BYTE', bytes) is executed, it displays:

Blob {size: 187086, type: ""}

however, it should actually display:

ArrayBuffer(187086)

As a result, the value of type is undefined.

This issue does not occur in another version of JavaScript without VUE, where everything works as expected.

I would greatly appreciate any assistance in identifying what might be causing this problem. Thank you!

Answer №1

To handle a blob stored in msg.data, you can utilize the arrayBuffer method belonging to the blob object. This method allows you to convert the blob into an ArrayBuffer and then create a Uint8Array from that buffer. It's important to note that the arrayBuffer operation is asynchronous, so it returns a promise.

For example:

function processMessage(msg) {
    if (typeof msg.data === "string") { 
        parseJSONString(msg.data);
        return;
    }
    
    msg.data.arrayBuffer()
    .then(buffer => new Uint8Array(buffer))
    .then(bytes => {
        console.log('Bytes:', bytes);
        const firstByte = bytes[0];
        switch (firstByte) {
            // Perform actions based on byte value
        }
    })
    .catch(error => {
        // Handle or report any errors that occur
    });
}

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

Upload multiple files using a single input field

Is there a way to upload multiple files using connected input blocks? Additionally, is it possible to store this data in an array of objects? https://i.sstatic.net/eOyrf.png ...

The information contained in HTML element lists and paginated using bootstrap and React does not persist after changing pages. This issue affects the functionality of React + Bootstrap

My "Pagination" Component manages the pagination of items (typically test questions) passed in as parameters. The component displays these items on the screen based on the current page. const dataTest = [ <><div className="row&quo ...

Javascript callback function

Greetings everyone! I've developed a simple nodesjs server using express. The server includes a login page where users enter their credentials to be checked against an Sqlite3 DB. My concern lies in the fact that the callback function only executes on ...

Creating a React.js component and setting an initial value within it

Recently delved into the world of React.js and currently attempting to create a reusable header that can switch between two states: one for when the user is logged in, and another for when the user is not logged in. // Header.js var Header = React.createC ...

Is there a way for mocha to conduct a recursive search within my `src` directory in order to find a specific

In my npm project, I want to replicate the structure used by Meteor: there is a source file called client.js and its corresponding test file named client.tests.js residing in the src/ directory. The tests should be executed with the npm test command. I am ...

What are the steps to integrate HJSON with Jest in a create-react-app development environment?

Currently, I am utilizing HJSON within a create-react-app project (view answer here). However, Jest does not utilize the same webpack configuration, resulting in a failed import of HJSON - for instance, import options from '../assets/options.hjson&ap ...

What is the process of sending a JavaScript request from a React application?

I have a button with the label "Show more". When this button is clicked, I want to load new objects dynamically without refreshing the page. const LoadMoreButton = ({ nextPageUrl }) => { const handleClick = e => { e.preventDefault(); const ...

Changing divider color in Material-UI with React

I need some assistance with changing the color of the divider component from the material ui framework. I have successfully changed colors for other components using the useStyles() method like this: const useStyles = makeStyles(theme => ({ textPad ...

Sending a string of HTML elements to a Vue custom directive is causing problems with the eslint code analysis

I have developed two custom Vue directives to add an HTML element before or after another element. I provide an HTML string to the element where I apply the directive, but I am encountering an error in VS Code: Parsing error: unexpected-character-in-a ...

Disable onclick action for programmatically created buttons

I'm facing an issue with the code I'm using to delete messages on my website. The problem is that while newly added messages are being dynamically loaded, the delete button (which links to a message deletion function) does not seem to be working. ...

"Animating a card to slide in from the left side upon clicking a button in a React app

How can we create a feature where, upon clicking "Apply Coupon" in Image 1, a window slides in from the left just above the webpage (as shown in Image 2)? Additionally, in Image 2, there is a blue transparent color on the webpage adjacent to this sliding w ...

Retrieving data depending on the Radio button choice

My objective is to fetch a cell value based on a selected radio button in a form and dynamically update a text area. The process involves the user opening a dialog box, selecting a field office, then triggering the 'check' function onClick. Foll ...

Finding a solution for the network error encountered during the execution of XMLHttpRequest.send in the specified file path (...distfxcoreservermain.js:200

Having recently delved into Angular, I successfully completed the development of my angular web application. While using ng serve for production, everything ran smoothly. However, after incorporating angular universal and attempting npm run dev:ssr or np ...

How to use AJAX to retrieve the text content of an HTML option value?

I have a script that displays a list of values, which I want to write: <option th:each = "iName : ${iNames}" th:value = "${iName}" th:text = "${iName}" th:selected="${selectedIName == iName}" In addition, I have the function setSelectedName in my .j ...

How can you direct a user to a specific page only when certain conditions are met?

Currently using React in my single page application. I have a good grasp on how Routes function and how to create a PrivateRoute. The issue arises when I need to verify the user's identity before granting access to a PrivateRoute. My attempt at imple ...

Unable to pass data to the onChange event for the material-ui datePicker components

Need help with a form that includes a material-ui DatePicker. Here is an example: <DatePicker name="startDate" autoOk={true} floatingLabelText="startDate" onChange={(x, event) => {console.log(arguments);}} /> When I change the date, the console ...

Is there an improved method for toggling animations in CSS using jQuery compared to my current approach?

Looking to create a toggle effect for a dropdown box that appears and disappears when a button is clicked. var clickState = false; $("#show").on("click", function() { if (!clickState) { $(".animated").removeClass("off"); refreshElement($(".an ...

struggles with integrating arrays into object attributes in JavaScript

When working with object attributes, keep in mind that they only hold the first element of the assigned value let groupedDepActivities=[] groupedDepActivities.push({ id:1, term_activity:{ terms:[{id:1},{from:'her ...

The issue with property unicode malfunctioning in bootstrap was encountered

I have tried to find an answer for this question and looked into this source but unfortunately, when I copy the code into my project, it doesn't display Unicode characters. section { padding: 60px 0; } section .section-title { color: #0d2d3e ...

Looking for a feature where users can easily update their profile using an interactive edit button

I'm currently working on a website project and one of the features I'm tackling is the user's profile page. My objective is to create an edit button within the page that allows the user to modify their name, username, email, and update their ...