I am trying to save a string to an external file using JavaScript. Below is what I am executing.
var mytext = "1111#1111"
var a = document.body.appendChild(document.createElement("a"));
a.download = "My_output.html";
a.href = "data:text/html," + mytext;
a.click();
This code works perfectly using Chrome. However with Firefox, it stops just prior to the "#". When I look at the resulting output file I see the following:
Results in Chrome look like this
1111#1111
Results in Firefox look like this
1111
It looks to me like the hashtag is breaking something. Can anyone help me understand why the "#" in a string is causing grief in Firefox but not Chrome? I have tried wrapping the string in double quotes as well as single quotes, but it does not appear to have any effect.
Any ideas?
You need to add URL Encoding to your string before you submit it.
var mytext = encodeURIComponent( "1111#1111" );
var a = document.body.appendChild(document.createElement("a"));
a.download = "My_output.html";
a.href = "data:text/html," + mytext;
a.click();
More information can be found here: encodeURIComponent
EDIT: And, this is just me btw, but why would you even do data:text/html? Just seems unnecessary.
You could just as easily submit this via Ajax (or use jQuery's $.ajax if you have that library available). If you happen to use jQuery, then all of this might be a little easier. Either way, hope that helps.
If I use this in firefox it comes out fine
var mytext = encodeURIComponent("1111#1111");
var a = document.body.appendChild(document.createElement("a"));
a.download = "My_output.html";
a.href = "data:text/html," + mytext;
a.click();
The trick is as always to encode uri components. And what you are passing along is in essense an uri component.
This way all special characters like ? # and + and % will be parsed correctly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With