How do I properly encode a mailto link with JSON data in the query parameters so that the link works as expected when some of the JSON data possibly includes spaces?
Here is a simple example:
var data = {
"Test": "Property with spaces"
};
var mailTo = 'mailto:?body=http://www.google.com/?body=' + JSON.stringify(data);
document.getElementById("link").href = mailTo;
The resulting link in the email after clicking the link looks like this:
Here is a JSBin showing what I am talking about:
https://jsbin.com/vuweyemeji/1/edit?html,js,output
Edit: Adding encodeURI() or encodeURIComponent() doesn't seem to work for me. I tried adding either of those methods around the data object and when I click the mailto link the url still looks the same in outlook.
You need to use
encodeURIComponent
twice, because you are encoding a parameter inside another parameter.Your link is using the
mailto
protocol and using abody
parameter which content should be encoded. But, inside that content you are entering a URL which has parameters, so, this parameters should be encoded also.Try this: