Base64 encoding fails for non-latin characters

Viewed 4304

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 Answers
Related