Book Image

JavaScript JSON Cookbook

By : Ray Rischpater, Brian Ritchie, Ray Rischpater
Book Image

JavaScript JSON Cookbook

By: Ray Rischpater, Brian Ritchie, Ray Rischpater

Overview of this book

Table of Contents (17 chapters)
JavaScript JSON Cookbook
About the Author
About the Reviewers

Encoding and decoding binary data as a base64 string using JavaScript in the browser

The base implementation of JavaScript does not include base64 encoding or decoding. However, all modern browsers include the atob and btoa methods to decode and encode base64 data respectively. These are methods of the window object, defined by the JavaScript runtime.

How to do it…

It's as easy as a method call:

var encodedData = window.btoa("Hello world"); 
var decodedData = window.atob(encodedData);

How it works…

The btoa function takes a string and returns the base64 encoding of that string. It's a method of the window object and calls to native browser code. The atob function does the reverse, taking a string containing base64 and returning a string with the binary data.

See also

For a summary of btoa and atob, see the Mozilla developer website at (note that while the documentation is from Mozilla, these methods of window...