btoa()
accepts a “string” where each character represents an 8-bit byte – if you pass a string containing characters that can’t be represented in 8 bits,
it willprobablybreak
. This isn’t a problem
if
you’re actually treating the string as a byte array, but if you’re trying to do something else then you’ll have to encode it first.
atob()
returns a “string” where each character represents an 8-bit byte – that is, its value will be between
0
and
0xff
. This does
not
mean it’s ASCII – presumably if you’re using this function at all, you expect to be working with binary data and not text.
let str = ‘
我叫
’
window.btoa(str) // InvalidCharacterError: String contains an invalid character
可以先将unicode text转换为utf-8编码(encodeURIComponent),然后使用base64编码,解码的时候再转换回来,就能得到原先的text
encodeURIComponent的转义范围比encodeURI更大