Is there a Base64 encoding function? window.btoa() doesn't seem to work

Is there a Base64 encoding function? While testing in chrome window.btoa() works but when you build for mac it doesn’t seem to work. I found base64Decode but I want to encode.

This is the code that requires it:

    var xhr = cc.loader.getXMLHttpRequest();
    var auth = 'Basic ' + window.btoa('jan' + ':' + 'jan');

    xhr.open('GET', 'http://localhost:7632/api/1/users', true);
    xhr.setRequestHeader('Authorization', auth);

I need base64 encode because using xhr.open(method,url,true, user, pass) is not working in Chrome. See this issue: https://code.google.com/p/chromium/issues/detail?id=128323

For anyone interested, I made a pull request. You can view it here:

https://github.com/cocos2d/cocos2d-js/issues/1511#issuecomment-77460676

Hi,
Try using this code.

Base64Encode = cc.Class.extend({
    ALPHABET: "HefghABCVWXYZabcdFGijDEIJKLMNOPQRpqrstuvwxyz0123456789-.STUklmno".split(""),
    encode: function (code) {
        return this._doEncode(this._toUTF8Array(code));
    },
_doEncode: function (buf) {
    var alphabet = this.ALPHABET;
    var size = buf.length;
    var ar = [];
    var a = 0;
    var i = 0;
    while (i < size) {
        var b0 = buf[i++];
        var b1 = (i < size) ? buf[i++] : 0;
        var b2 = (i < size) ? buf[i++] : 0;

        var mask = 0x3F;
        ar[a++] = alphabet[(b0 >> 2) & mask];
        ar[a++] = alphabet[((b0 << 4) | ((b1 & 0xFF) >> 4)) & mask];
        ar[a++] = alphabet[((b1 << 2) | ((b2 & 0xFF) >> 6)) & mask];
        ar[a++] = alphabet[b2 & mask];
    }
    switch (size % 3) {
        case 1:
            ar[--a] = '_';
        case 2:
            ar[--a] = '_';
    }

    return ar.join("");
},

_toUTF8Array: function (str) {
    var utf8 = [];
    for (var i = 0; i < str.length; i++) {
        var charcode = str.charCodeAt(i);
        if (charcode < 0x80) utf8.push(charcode);
        else if (charcode < 0x800) {
            utf8.push(0xc0 | (charcode >> 6),
                0x80 | (charcode & 0x3f));
        }
        else if (charcode < 0xd800 || charcode >= 0xe000) {
            utf8.push(0xe0 | (charcode >> 12),
                0x80 | ((charcode >> 6) & 0x3f),
                0x80 | (charcode & 0x3f));
        }
        // surrogate pair
        else {
            i++;
            // UTF-16 encodes 0x10000-0x10FFFF by
            // subtracting 0x10000 and splitting the
            // 20 bits of 0x0-0xFFFFF into two halves
            charcode = 0x10000 + (((charcode & 0x3ff) << 10)
            | (str.charCodeAt(i) & 0x3ff));
            utf8.push(0xf0 | (charcode >> 18),
                0x80 | ((charcode >> 12) & 0x3f),
                0x80 | ((charcode >> 6) & 0x3f),
                0x80 | (charcode & 0x3f));
        }
    }
    return utf8;
}
});

var Base64Encode = new Base64Encode();

How to use?
Base64Encode.encode("string");

can you fix it? . This don’t use…