encodeURIComponent inline on onClick - javascript

I have a link on my page, that when clicked calls a method with 2 arguments. One of these arguments may have special characters (ie ' or é etc.). I get page errors when I try to pass such variables, so I am trying to encode them before passing them. How can I call encodeURIComponent inline?
I am trying to do this:
<a title="${facet.toolTipDisplay}" onclick="submitFacet('Company', '${encodeURIComponent(facet.javaScriptVar)}')">
And I seem to be getting the error:
SEVERE: Servlet.service() for servlet jsp threw exception
org.apache.jasper.JasperException: /WEB-INF/pages/SearchForm.jsp(831,126) The function encodeURIComponent must be used with a prefix when a default namespace is not specified
DISCLAIMER: I am new to web stuff and only have access to the JSP page and not the java class where the facet.javaScriptVar is coming from.

Hi you are trying to use Java or JS to encode your UI component?. The easiest way I think is to use JS functions . Encoding method will depend on characters to encode, from less exclusive to most you have escape (not suitable for uris), encodeUri and encodeUriComponent
<a title="${facet.toolTipDisplay}" onclick="submitFacet('Company',
'encodeURIComponent(${facet.javaScriptVar})'">
To be more polite you could apply encoding inside your submitFacet function, just passing Company and your JSTL var.
Reading your comments I would suggest to escape va content before treat it with JS otherwise wouldn't be possible.
Try one of this 2 approaches:
onclick="submitFacet('<c:out value="${facet.javaScriptVar}"/>')"
onclick="submitFacet('${fn:escapeJava(facet.javaScriptVar)}')"
Assuming you import Apache taglib.

I decided to go with just replacing the apostrophe with "\'" (escaped apostrophe). When my function is called the escaped apostrophe is replaced with the apostrophe like normal.
This is what it looks like within the HTML:
// arguments = Company, L\'Oréal (4)
onclick="submitFacet('Company', '${fn:replace(facet.toolTipDisplay, "'", "\\'")}')"
Then what it looks like when the submitFacet function is called:
"Company", "L'Oréal (4)"

Related

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:
Link
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.
E.G.
<element attribute=""">
<element attribute='''>
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
Link
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 ") 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.

CL-WHO is always starting with a single quote

My issue is that CL-WHO begins each expression with a single quotation market when it turns the Lisp S-expressions into html output. This is okay most of the time, but it is an issue since I am linking my file to an external javascript file. I am trying to make this project simple, and since none of the javascript developers on my team know Common Lisp, using parenscript is likely out of the equation. Here is an example of my issue and one of the errors in my program:
:onclick "alertUser('id')"
When a particular element is pressed within the html document, this should trigger a JavaScript function called alertUser, and the id of the tag should be passed to the JavaScript function as an argument. But no matter what I do, CL-WHO will convert that string into single quotation marks, so I end up with an invalid expression. Here is what that code converts to:
onclick='alertUser('id')'>
Everything is a single quotation so 'alertUser(' is passed as the first string which is obviously invalid and I receive a syntax area in my developer tools. I thought that I could solve this problem by using the format function with escape characters. This would equate to:
CL-USER> (format t "\"alertUser('id')\"")
"alertUser('id')"
NIL
CL-USER>
But when I try that with CL-WHO:
:onclick (format nil "\"alertUser('id')\"")
That translates to:
onclick='"alertUser('locos-tacos-order')"'>
Which is also invalid html. As you can see, CL-WHO will start with a single quote no matter what. Next I tried the CL-WHO fmt function:
:onclick (fmt "\"alertUser('locos-tacos-order')\"")
When I use the fmt function it gets rid of my :onclick expression entirely when it is converted to html!:
id='id'"alertUser('id')">
Lastly I tried the str function, and got similarly invalid output to my original attempt:
onclick='"alertUser('id')"'
Obviously if I code this in pure html it will look like:
onclick="alertUser('id')">
Which is valid.
My question is simply how do I enable CL-WHO to use double quotation marks in these situations instead of single quotation marks?
#jkiiski was has the correct answer in the comments underneath my question, but I wanted to post the answer so that anyone with a similar issue in the future can resolve the problem. As #jkiiski said, there is a variable called ATTRIBUTE-QUOTE-CHAR in the cl-who package that defaults to #\'. You can simply set that variable to #\" instead in order for the default quotations used to be double quotation marks:
(setf *attribute-quote-char* #\")
After adding that line of code near the top of the file my html defaults to:
onclick="alertUser('id')"
and now the javascript can execute properly. Credit to #jkiiski for a correct answer.

How to Use ES6 Template Literals in Freemarker? [duplicate]

I'm trying to use Freemarker in conjunction with jQuery Templates.
Both frameworks use dollar sign/curly brackets to identify expressions for substitution (or as they're called in freemarker, "interpolations") , e.g. ${person.name} .
So when I define a jQuery Template with expressions in that syntax, Freemarker tries to interpret them (and fails).
I've tried various combinations of escaping the ${ sequence to pass it through Freemarker to no avail - \${, \$\{, $\{, etc.
Inserting a freemarker comment in between the dollar and the curly (e.g. $<#-- -->{expression}) DOES work - but I'm looking for a more concise and elegant solution.
Is there a simpler way to get a Freemarker template to output the character sequence ${?
This should print ${person.name}:
${r"${person.name}"}
From the freemarker docs
A special kind of string literals is the raw string literals. In raw string literals, backslash and ${ have no special meaning, they are considered as plain characters. To indicate that a string literal is a raw string literal, you have to put an r directly before the opening quotation mark or apostrophe-quote
For longer sections without FreeMarker markup, use <#noparse>...</#noparse>.
Starting with FreeMarker 2.3.28, configure FreeMarker to use square bracket syntax ([=exp]) instead of brace syntax (${exp}) by setting the interpolation_syntax configuration option to square_bracket.
Note that unlike the tag syntax, the interpolation syntax cannot be specified inside the template. Changing the interpolation syntax requires calling the Java API:
Configuration cfg;
// ...
cfg.setInterpolationSyntax(SQUARE_BRACKET_INTERPOLATION_SYNTAX);
Then FreeMarker will consider ${exp} to be static text.
Do not confuse interpolation syntax with tag syntax, which also can have square_bracket value, but is independent of the interpolation syntax.
When using FreeMarker-based file PreProcessor (FMPP), either configure the setting via config.fmpp or on the command-line, such as:
fmpp --verbose --interpolation-syntax squareBracket ...
This will call the appropriate Java API prior to processing the file.
See also:
https://freemarker.apache.org/docs/dgui_misc_alternativesyntax.html
http://fmpp.sourceforge.net/settings.html#templateSyntax
Another option is to use #include with parse=false option. That is, put your jQuery Templates into the separate include page and use parse=false so that freemarker doesn't try and parse it.
This would be a good option when the templates are larger and contain double quotes.
I had to spent some time to figure out the following scenarios to escape ${expression} -
In Freemarker assignment:
<#assign var = r"${expression}">
In html attribute:
Some link
In Freemarker concatenation:
<#assign x = "something&"+r"${expression}"/>
If ${ is your only problem, then you could use the alternate syntax in the jQuery Templates plugin like this: {{= person.name}}
Maybe a little cleaner than escaping it.
Did you try $$?
I found from the Freemarker manual that ${r"${person.name}"} will print out ${person.name} without attempting to render it.
Perhaps you should also take a look at Freemarker escaping freemarker
I can confirm that the
${r"${item.id}"}
is the correct way as an example.
So I kinda full example will look like
<span> Remove </span>
and the output will be :
<span> Remove </span>
In the case when you want to use non-raw strings so that you can escape double quotes, apostrophes, etc, you can do the following:
Imagine that you want to use the string ${Hello}-"My friend's friend" inside of a string. You cannot do that with raw strings. What I have used that works is:
${"\x0024{Hello}-\"My friend's friend\""}
I have not escaped the apostrophe since I used double quotes.

Escape quotes in Javascript/Chameleon template

I am trying to pass a python dictionary from a chameleon template to a javascript function. But since the dictionary contains single quotes or ' which need to be escaped I get an error in firebug that says : SyntaxError: missing ) after argument list.
My code looks like this:
<div id = "divsfp">
<input type="button" id="sfp" value="SFP"
onclick="get_sfp('${dict_value}')"></input></div>
Where dict_value is a python dictionary. How can I escpae ' in chameleon template before passing the data or in Javascript function itself?
You need to JSON encode the dictionary. You don't then need to put quotes around the dictionary, and JavaScript will see it as a JavaScript object.
Use double-quotes, encoded as &quot:
onclick="get_sfp("${dict_value}")"
Chameleon will escape any double-quotes in dict_value.
You can try this, if this helps
"get_sfp('"+${dict_value}+"')"
Also from your implementation it seems that the dict_value is the variable you already know. So whats the problem accessing it from the get_sfp function.
Sorry couldn't comment as I still don't have that privilege.

javascript escape problem with unicode characters

I use the following jquery code to load some date on a specific event from external file:
$("#container").load("/include/data.php?name=" + escape(name));
if the javascript "name" variable contains unicode characters it sends some encoded symbols to data.php file, something like this: %u10E1
How can I deal with this encoded symbols? I need to convert them back to readable one.
When I remove the escape function and leave just "name" variable the code doesn't work any more...
Can anyone please help?
If you want to do this manually, then you should be using encodeURIComponent, not escape (which is deprecated)
The jQuery way, however, would be:
$("#container").load("/include/data.php", { "name": name });
Either way PHP should decode it automatically when it populates $_GET.
This may help you.
javascript - how to convert unicode string to ascii

Categories

Resources