简体   繁体   中英

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.

HTML character entities and escapes are replaced by the HTML parser when parsing source. For quotation marks, it allows inclusion of the same kind of quotation mark in an HTML attribute that is being used to quote the attribute value in source.

EG

 <element attribute="&quot;">
 <element attribute='&#039;'>

in source would produce attribute values of " (double quote) and ' (single quote) respectively, despite being the delimters used to quote the attribute value in HTML source.

Hence

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

will produce an href attribute value of

  javascript:uploadVariantPicture('size:'test'');

after removal of the outer double quotes by the HTML parser.

Options could include escaping double quotes (HTML &quot; ) inside the href value appropriately (it depends on the syntax accepted by uploadVariantPicture ), including backslash escapes before the single quotes as mentioned in the post, or not using the javascript: pseudo protocol at all, in favor of adding an event listener in JavaScript.

Not using javascript: pseudo protocol is highly recommended - basically it's a hold over from HTML3.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM