在 JavaScript 中解码 URL Safe Base64(浏览器端)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28100601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:24:51  来源:igfitidea点击:

Decode URL Safe Base64 in JavaScript (browser side)

javascriptbase64gmail-api

提问by wibberding

I am using Gmail's API to get emails from my account. The body of the message is delivered in a "URL safe base64" format. What is the best way to decode this for use? I have found some nodejs solutions, but no client side ones. window.atob does not work since it is URL safe.

我正在使用 Gmail 的 API 从我的帐户中获取电子邮件。邮件正文以“URL 安全 base64”格式传送。解码它以供使用的最佳方法是什么?我找到了一些 nodejs 解决方案,但没有找到客户端解决方案。window.atob 不起作用,因为它是 URL 安全的。

Thanks for any help.

谢谢你的帮助。

回答by xori

For posterity,

为后人,

atob(data.replace(/_/g, '/').replace(/-/g, '+'))

As stated by the spec https://tools.ietf.org/html/rfc4648#section-5however because this uses atob()it does not support unicode characters and thus requires a polyfill.

正如规范https://tools.ietf.org/html/rfc4648#section-5所述,但是因为它使用atob()它不支持 unicode 字符,因此需要polyfill

回答by wibberding

Finally found it. This does URL Safe decoding

终于找到了。这做 URL 安全解码

https://github.com/dankogai/js-base64

https://github.com/dankogai/js-base64

回答by Daniel Weiner

decodeURIComponent(atob(data))

decodeURIComponent(atob(data))