1

I have a tool I'm building for writing blog posts. I was wondering if it is possible to take the value of a textarea -> encode with base64 -> set as URL hash without refresh.

The values should be equal between the textarea and hash. If one updates then so does the other. That way all the client has to do is share the URL and the textarea will load.

Thanks in advance!

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Note that there's a limit on the number of characters you can have in your URL. Blog posts can be pretty long, so you're likely to run into that limit. Here's a relevant question: http://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-a-url-in-different-browsers Also, base64 encoded strings are longer than their originals. – Assan Jan 04 '17 at 19:18

1 Answers1

0

You can use the btoa() method to base64 encode a string. From there you can simply update the fragment of the URL using window.location.hash. Try this:

$('textarea').on('input', function() {
  var encodedValue = btoa(this.value);
  window.location.hash = encodedValue;
  
  $('div').text(encodedValue); // only to show the encoded output in this demo
});
textarea { width: 100%; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea></textarea>

<div></div>

Note that btoa() is unsupported in < IE10 so if you need to support legacy browsers you will need an alternative implementation. There are lots already available if you Google.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339