javascriptjquerysegment-io

Prevent `document.execCommand("copy")` from replacing ampersands


I have a tool which generates URLs, and a button for copying the generated URL to the clipboard. This function does successfully copy my URL:

function copyUrlToClipboard() {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val(myUrl).select();
  document.execCommand("copy");
  $temp.remove();
}

However, in the copied URL, ampersand characters are replaced with &amp%3B. For example, the url

mysite.com/?utm_source=se&utm_medium=foo

becomes

mysite.com/?utm_source=se&amp%3Butm_medium=foo

Unfortunately I use segment/amplitude analytics downstream, which fails to extract parameters from this URL.

Why does this happen? Is there a way to change the behaviour of copy, or some post-processing I can do on the clipboard item? Failing that, does anybody know if segment can be configured to be smarter about parameter extraction?

Update:

Upon investigation it appears that $temp.val() is responsible for replacing & with &amp; (I'm not sure what the term for this is - sanitizing it?) and then upon pasting the url in the browser the ; is sanitized as %3B. But I don't understand why val() is being sanitized, is there a property/attribute I can set on my temp element, or a different type of element to use?


Solution

  • I figured it out thanks to comment suggestions. It was because myUrl was coming from a django template variable:

    {{ original.my_url }}

    As it turns out I had to mark this variable as safe:

    {{ original.my_url | safe }}

    This now copies the url without modification. Thank you for the suggestions!