iT邦幫忙

2

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')
  ))));
}

https://ithelp.ithome.com.tw/upload/images/20200331/20124031ZVZDQuRgAi.png

參考來源:

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

尚未有邦友留言

立即登入留言