5

I'm working on a VueJS project where I generate SVG images based on input. After they have been generated, I send data from them to a back end API as a base64 encoded string.

Now, whenever I try to encode the string with UTF8 characters, I get the following error:

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

I tried to solve the issue with replacing all characters in the HTML with their Unicode code points. However, whenever I try to get the DOM element, the Unicode encoded characters are reverted back to their plain text format.

How can I obtain the HTML as a base64 encoded string?

The issue can be seen in a fiddle here.

I've tried both using XMLSerializer and just running innerHTML.toString():

let svgEl = this.$el.querySelector('.svg-container svg')
if (!svgEl) {
  console.log('no poster element')
  return
}

// Using XMLSerializer:
console.log(btoa(new XMLSerializer().serializeToString(posterEl))

// Using innerHTML:
console.log(btoa(posterEl.innerHTML.toString()))

Both the above examples yield the same error.

Thanks.

  • 1
    https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#The_Unicode_Problem – Evert Oct 26 '18 at 22:45

1 Answers1

1

You can follow the answer steps in for this answered question: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.

The key of solution is to encode the string by this way:

btoa(unescape(encodeURIComponent(str)));
Mohamed Abulnasr
  • 589
  • 7
  • 18