Tom
Tom

Reputation: 5201

Encoding a string (in UTF-8) as binary data in JavaScript cross-browser

I am developing a web page that communicates with the server via AJAX. The server is expecting binary data in a specific format. At the moment my JavaScript code can generate the entire data the server is expecting, except for one part which consists of a UTF-8 representation of some string parameter.

In short, what I need is a JavaScript function that gets a string s and returns its UTF-8 representation as a Uint8Array.

This is very easy in Firefox, which has the TextEncoder class:

function utf8(s) {
  return new TextEncoder().encode(s);
}

Unfortunately, Firefox is not the only browser out there ;-) Does anyone know of a way to do this cross-browser?

I could write up my own encoder, but I'd rather use something native if it's possible.

Note: I would gladly welcome a non-cross-browser solution as long as it works on Google Chrome.

Upvotes: 1

Views: 3081

Answers (1)

Kevin Hakanson
Kevin Hakanson

Reputation: 42200

There is a polyfill for the Encoding Living Standard API, which TextEncoder is part of.

TextEncoder is shipping in Chrome 38. See Encoding API entry from Chromium Dashboard and Chromium Issue 398149: Text Encoding API.

Upvotes: 1

Related Questions