JavaScript atob / btoa 编解码不支援 utf8 的解决方案

url get 传参数

解析utf8字元(中文)
发生

Uncaught DOMException: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.

没想到经过网址get传参数
编码后的"+",这个字元会因为searchParams.get(),而导致被替换成" "(空白字元)

// 使用utf-8字符集进行base64编码function utoa(Object) {    btoa(unescape(encodeURIComponent(JSON.stringify(Object))))}// https://example.com?data=eyJ0aXRsZSI6IuaWsOWMl+eSsOeLgOe3muW9ouixoeW7o+WRiiJ9// 使用utf-8字符集解析base64字符串 function atou() {    githubURL = new URL(window.location);    JSON.parse(decodeURIComponent(escape(atob(        githubURL        .searchParams        .get('data')        .replace(/-| /g, "+")        .replace(/_/g, "/")        .replace(/%/g, '%25')  ))));}

http://img2.58codes.com/2024/20124031ZVZDQuRgAi.png

参考来源:

https://matthung0807.blogspot.com/2020/03/javascript-base64-encode-decode.htmlhttp://levy.work/2017-03-24-black-magic-js-atob-with-utf8/https://www.jianshu.com/p/82afa633033e

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章