please, Please, PLEASE, don't use atob/btoa

edited May 2012 in Enyo 2
Most of browser implementations of Base64 encoding/decoding are wrong, at best. They always get wrong output for non-English characters.

Use this one instead (if possible):


  • Interesting... Is this because they're treating the string as UTF-8 going into the btoa call? I've seen various issues depending on how the browser loads my script files, which makes me think we need to modify the Enyo loader to start specifying charset attributes.
  • edited May 2012
    The issue comes both with encoding and decoding, and yes, definitely atob and btoa methods threat them differently. Look at the fiddle:

    In the utf8 + base64 encoded I'm massaging the string with webtoolkit's Base64._utf8_encode() method, and then enyo.string.toBase64() gives the right output.

    I assume it will be the same for enyo.string.fromBase64() and Base64._utf8_decode()
  • Thanks for the fiddle -- I've filed this as and hope to adjust things after consulting with the team.
  • @rafa_bernad‌ - old thread, I know, but I think you've misunderstood what btoa() and atob() do.

    They are encoding-agnostic, and don't (& shouldn't!) make any assumptions about encoding used. Since only 8-bit characters can be directly encoded as base64, it's up to you to convert Unicode characters into whatever 8-bit encoding you wish to use (admittedly, this would rarely be anything other then UTF-8).

    For UTF-8 strings, this conversion is most easily done by window.btoa( unescape( encodeURIComponent( str ) ) ) and decodeURIComponent( escape( window.atob( str ) ) ).

    This is more fully explained in Mozilla's article on Base64 encoding and decoding:

    So btoa/atob are not wrong, you just need to understand what they do and how to use them.
Sign In or Register to comment.