javascriptjqueryhtmlspecialcharssingle-quotes

Despite single quotes being encoded using htmlspecialchars, JavaScript is still complaining that these quotes need to be escaped in the function call


Something strange is occurring and I'm stumped.

I have a link that looks basically like this:

<a href="javascript:uploadVariantPicture('size:&#039;test2&#039');">Link</a>

As you can see, I'm calling function uploadVariantPicture with parameter "size:'test2&#039".

However, when I actually click the link, JavaScript complains that the two encoded single quotes aren't being escaped. I'm getting the following error:

SyntaxError: Unexpected identifier 'test2'. Expected ')' to end an argument list.

If I decode the two encoded single quotes and escape them using a backslash, then the function call succeeds. But the problem is I need it encoded. I cannot leave it unencoded and escape the quotes. This won't work for my situation.

Any help is greatly appreciated. I'm super confused.


Solution

  • Consider attaching an event handler properly using JavaScript instead so you don't have to worry about escaping issues, and so that you don't have to rely on the pollution of the global object for the script to work:

    const uploadVariantPicture = (arg) => console.log(arg);
    
    document.querySelector('a').addEventListener('click', () => {
      uploadVariantPicture("size:'test2'");
    });
    <a>Link</a>

    I can't think of any situations in which an inline handler would be preferable to addEventListener, unless you were deliberately trying to exploit an XSS vulnerability.