javascript エラー「Uncaught DOMException: Failed to execute ‘btoa’ on ‘Window’: The string to be encoded contains characters outside of the Latin1 range.」の解決方法

javascript エラー「Uncaught DOMException: Failed to execute ‘btoa’ on ‘Window’: The string to be encoded contains characters outside of the Latin1 range.」の解決方法

javascriptで、エラー「Uncaught DOMException: Failed to execute ‘btoa’ on ‘Window’: The string to be encoded contains characters outside of the Latin1 range.」が発生した場合の原因と解決方法を記述してます。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 103.0.5060.66

エラー内容

以下のコードを実行した際に発生。

console.log( btoa( 'あいうえお') );

エラーメッセージ

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

画像

firefox102の場合は、以下のエラーが発生します。

Uncaught DOMException: String contains an invalid character

画像

原因

日本語を「bota」にそのまま使用すると「base64」にエンコードできない

解決方法

「encodeURIComponent」と「unescape」を使用する

console.log( btoa( unescape ( encodeURIComponent('あいうえお') ) ) );