Javascript with Special Chartecter - javascript

I have a html page in which I need to pass a String variable to javascript function. This works until String does not have a special charecter.
<html>
<head>
<script>
function test(v){
alert(v);
}
</script>
</head>
<body>
<input type="button" value="Test Button" onClick="test('BlahBlah')"/>
</body>
</html>
As soon as I change onClick like below, it stops working.
onClick="test('Blah'Blah')"
Any solution for this problem. Please take a note parameter which is being passed to JavaScript function is dynamic.Source of Parameter is backend and I cannot change that peice of code. Second thing even if put escape it still does not work. My problem is I have to retian the special charecter for some processing at backend

There are two layers to this:
The content of onClick attributes, like all attributes, is HTML text. That means that any character that's special in HTML (like <) must be replaced with an HTML entity (e.g., <). Additionally, if you use double quotes around the attribute value, any double quotes within the value must be replaced with entities ("); if you used single quotes around the attribute, you'd need to replace ' with &apos;.
Your attribute contains a JavaScript string literal. That means that any characters that are special inside JavaScript string literals must be escaped according to the JavaScript rules. Since you've used single quotes to delimit the JavaScript string, for instance, you have to escape any single quotes in the string with a backslash.
I'm assuming that HTML is generated server-side. If so, the work above must be done server-side, when building the HTML of the page. You haven't said what server-side tech you're using, so it's hard to point you at solutions that your server-side tech/environment might provide.
In the simple case of your
onClick="test('Blah'Blah')"
...you just need to add the backslash within the JavaScript string
onClick="test('Blah\'Blah')"
...but that's just that one specific case.
The dramatically simpler option is to not put JavaScript code in attribute values. Instead, use modern techniques (addEventListener, attachEvent) to hook up JavaScript code.
But if you must use an onClick attribute, avoid having text in it (or deal with the complexities above); have it call a function defined in a script element that then has the text, as you then have only the one layer (#2 above) to deal with.
Source of Parameter is backend and I cannot change that peice of code.
That backend is broken and needs fixing.
If:
the backend is only producing invalid JavaScript code (not invalid HTML)
and the code consists of a single function call
and the code is always a single function call
and the function call always has a single string literal argument
and that argument is always delimited with single quotes
and the single quotes within the string are never correctly escaped
...we might be able to salvage it client-side. But my guess is that the backend will also produce invalid HTML, for instance when the text has a " in it. (We can't do anything about that, because the attribute value will be chopped off at that point.)
But let's keep a good thought: Given the ridiculous list of caveats above, this might do it:
var elm = document.getElementById("the-div");
var code = elm.getAttribute("onclick");
var m = code.match(/^([^(]+)\('(.*)'\)$/);
if (m) {
code = m[1] + "('" + m[2].replace(/'/g, "\\'") + "')";
}
elm.setAttribute("onclick", code);
Live Example:
function foo(str) {
alert(str);
}
var elm = document.getElementById("the-div");
var code = elm.getAttribute("onclick");
var m = code.match(/^([^(]+)\('(.*)'\)$/);
if (m) {
code = m[1] + "('" + m[2].replace(/'/g, "\\'") + "')";
}
elm.setAttribute("onclick", code);
<div id="the-div" onclick="foo('blah'blah')">Click me</div>

Well this is an very common problem you wanted to add single quotes inside single quotes to do this you have to escape that Sigle quotes to do that you have to put an forward slash.
onClick="test('Blah\'Blah')"

Related

Javascript How to escape \u in string literal

Strange thing...
I have a string literal that is passed to my source code as a constant token (I cannot prehandle or escape it beforehand).
Example
var username = "MYDOMAIN\tom";
username = username.replace('MYDOMAIN','');
The string somewhere contains a backslash followed by a character.
It's too late to escape the backslash at this point, so I have to escape these special characters individually like
username = username.replace(/\t/ig, 't');
However, that does not work in the following scenario:
var username = "MYDOMAIN\ulrike";
\u seems to introduce a unicode character sequence. \uLRIK cannot be interpreted as a unicode sign so the Javascript engine stops interpreting at this point and my replace(/\u/ig,'u') comes too late.
Has anybody a suggestion or workaround on how to escape such a non-unicode character sequence contained in a given string literal? It seems a similar issue with \b like in "MYDOMAIN\bernd".
I have a string literal that is passed to my source code
Assuming you don't have any < or >, move this to inside an HTML control (instead of inside your script block) or element and use Javacript to read the value. Something like
<div id="myServerData">
MYDOMAIN\tom
</div>
and you retrieve it so
alert(document.getElementById("myServerData").innerText);
IMPORTANT : injecting unescaped content, where the user can control the content (say this is data entered in some other page) is a security risk. This goes for whether you are injecting it in script or HTML
Writing var username = "MYDOMAIN\ulrike"; will throw a syntax error. I think you have this string coming from somewhere.
I would suggest creating some html element and setting it's innerHTML to the received value, and then picking it up.
Have something like:
<div id="demo"></div>
Then do document.getElementById("demo").innerHTML = username;
Then read the value from there as document.getElementById("demo").innerHTML;
This should work I guess.
Important: Please make sure this does not expose the webpage to script injections. If it does, this method is bad, don't use it.

Havoc while escaping quotes in Javascript

I am trying to build a custom HTML/Javascript command using the following Javascript (for now, "dialogText" contains the name of a vegetable, but it may later contain HTML tags too):
str = str + "<span onClick=showDialog('"+dialogText+"')>";
When dialogText is only one word long (i.e. "Basil"), this works correctly, giving the following result:
<span onclick="showDialog('Basil')">
But when dialogText includes more than one word (i.e. "Beet root"), this fails. The result is syntactically invalid and generates a Javascript error:
<span onclick="showDialog('Beet" root')="">
Why does this happen (where did the equals sign come from?)?
And how can I change the code so that it works?
You aren't looking at the HTML you are generating, you are converting that HTML to a DOM and then serializing it back to HTML.
Since you have a " as data in the attribute value, but haven't represented it as a character reference ("), and the value is limited with " - the " ends the attribute.
You then start a new attribute.
Since the next attribute doesn't have a value, it gets assigned an empty string when the browser attempts to error correct.
In general, avoid mashing strings together to generate HTML for conversion to a DOM. Use DOM methods directly instead.
var span = document.createElement('span');
span.addEventListener('click', function (event) {
showDialog(dialogText);
});

How do you define a string in JavaScript that could contain any character?

Even though I'm using a Salesforce variable in my JavaScript, it is not necessary to know Salesforce to answer my question. There's a password field I want to access. I can do this by using the Salesforce variable, {!Account.Password__c}, inside my JavaScript like so:
var p = '{!Account.Password__c}';
I've been using this for a long time, but there are some instances where it doesn't work. The only problem is that the password could contain any character (as a good password should). So if it contains a single quote, then this JavaScript will not run. I could write it with double quotes:
var p = "{!Account.Password__c}";
But it could contain a double quote also. It could also contain forward slashes and/or back slashes.
The password string needs to be able to take any of these:
Idon'tknow
pass"word"
/-\_|)_/-\_/\/\
"'!##
+*co/rn
This is my code:
var u = '{!Account.Email_Address__c}';
var p = escape(encodeURIComponent('{!Account.Password__c}'));
window.open('http://mywebsite.com/?&u=' + u + '&p=' + p,'_blank');
What you're looking for is the JSENCODE function. It will escape quotes, backslashes, and anything else that might mess up your Javascript string.
var p = '{!JSENCODE(Account.Password__c)}';
If your Javascript is inside an HTML tag (eg: in an 'onclick' attribute) then use the JSINHTMLENCODE function, which will html-encode the characters <&> .
These are documented in the Visualforce Functions reference.
Your problem is that of escaping. You can backslash any character in a string - so if you have, say, owowow"'!thisishard as a password, to assign it straight up to a JS var, you would do this:
var p = "owowow\"\'!thisishard";
Which deals with the escaping. You do not need to do this if you have acquired the variable from another source (say, a text element through element.value).
This does not reove a couple of issues:
Passing passwords through GET params is pretty high up on the OWASP guidelines of things not to do. The reason being that they will show up on server logs in addition to being sniffable through conventional means.
Why on earth are you doing this?

How to deal with sigle quote in javascript in jsp page?

onclick= "_deleteWPSchemeData(${viewWPMasterGrid.id}, '${viewWPMasterGrid.name}')"
${viewWPMasterGrid.name} retutrns me a string(for e.g. W.P.WINT OFF ALL'10) which often has single quote character so from the calling javascript method I am not getting the second parameter at all. How to deal with problem?
When a dynamic String can be put inside a JavaScript string literal, it should be JS-escaped. Just as when a dynamic String is put inside a HTML page, it's HTML-escaped.
Use commons-lang StringEscapeUtils.escapeECMAScript (or escapeJavaScript depending on the version) to escape the String. You could create a very simple EL function to do that straight from the JSP.
Note that you could have problems with single quotes, but also double quotes, tags, EOLs, backslash, which must all be escaped in a JS String literal.
It looks like you could split the second parameter out into its own variable first. If I have understood your question correctly.
var viewWPMasterGridName = "${viewWPMasterGrid.name}";
onclick = "_deleteWPSchemeData(${viewWPMasterGrid.id},'" + viewWPMasterGridName + "')";
Use '${viewWPMasterGrid.name.replaceAll("'", "\'")}'
try this,
var name = "${viewWPMasterGrid.name}".replace(/'/g,"\\'");

How do I escape a string inside JavaScript code inside an onClick handler?

Maybe I'm just thinking about this too hard, but I'm having a problem figuring out what escaping to use on a string in some JavaScript code inside a link's onClick handler. Example:
Select
The <%itemid%> and <%itemname%> are where template substitution occurs. My problem is that the item name can contain any character, including single and double quotes. Currently, if it contains single quotes it breaks the JavaScript code.
My first thought was to use the template language's function to JavaScript-escape the item name, which just escapes the quotes. That will not fix the case of the string containing double quotes which breaks the HTML of the link. How is this problem normally addressed? Do I need to HTML-escape the entire onClick handler?
If so, that would look really strange since the template language's escape function for that would also HTMLify the parentheses, quotes, and semicolons...
This link is being generated for every result in a search results page, so creating a separate method inside a JavaScript tag is not possible, because I'd need to generate one per result.
Also, I'm using a templating engine that was home-grown at the company I work for, so toolkit-specific solutions will be of no use to me.
In JavaScript you can encode single quotes as "\x27" and double quotes as "\x22". Therefore, with this method you can, once you're inside the (double or single) quotes of a JavaScript string literal, use the \x27 \x22 with impunity without fear of any embedded quotes "breaking out" of your string.
\xXX is for chars < 127, and \uXXXX for Unicode, so armed with this knowledge you can create a robust JSEncode function for all characters that are out of the usual whitelist.
For example,
Select
Depending on the server-side language, you could use one of these:
.NET 4.0
string result = System.Web.HttpUtility.JavaScriptStringEncode("jsString")
Java
import org.apache.commons.lang.StringEscapeUtils;
...
String result = StringEscapeUtils.escapeJavaScript(jsString);
Python
import json
result = json.dumps(jsString)
PHP
$result = strtr($jsString, array('\\' => '\\\\', "'" => "\\'", '"' => '\\"',
"\r" => '\\r', "\n" => '\\n' ));
Ruby on Rails
<%= escape_javascript(jsString) %>
Use hidden spans, one each for each of the parameters <%itemid%> and <%itemname%> and write their values inside them.
For example, the span for <%itemid%> would look like <span id='itemid' style='display:none'><%itemid%></span> and in the javascript function SelectSurveyItem to pick the arguments from these spans' innerHTML.
If it's going into an HTML attribute, you'll need to both HTML-encode (as a minimum: > to > < to &lt and " to ") it, and escape single-quotes (with a backslash) so they don't interfere with your javascript quoting.
Best way to do it is with your templating system (extending it, if necessary), but you could simply make a couple of escaping/encoding functions and wrap them both around any data that's going in there.
And yes, it's perfectly valid (correct, even) to HTML-escape the entire contents of your HTML attributes, even if they contain javascript.
Try avoid using string-literals in your HTML and use JavaScript to bind JavaScript events.
Also, avoid 'href=#' unless you really know what you're doing. It breaks so much usability for compulsive middleclickers (tab opener).
<a id="tehbutton" href="somewhereToGoWithoutWorkingJavascript.com">Select</a>
My JavaScript library of choice just happens to be jQuery:
<script type="text/javascript">//<!-- <![CDATA[
jQuery(function($){
$("#tehbutton").click(function(){
SelectSurveyItem('<%itemid%>', '<%itemname%>');
return false;
});
});
//]]>--></script>
If you happen to be rendering a list of links like that, you may want to do this:
<a id="link_1" href="foo">Bar</a>
<a id="link_2" href="foo2">Baz</a>
<script type="text/javascript">
jQuery(function($){
var l = [[1,'Bar'],[2,'Baz']];
$(l).each(function(k,v){
$("#link_" + v[0] ).click(function(){
SelectSurveyItem(v[0],v[1]);
return false;
});
});
});
</script>
Another interesting solution might be to do this:
Select
Then you can use a standard HTML-encoding on both the variables, without having to worry about the extra complication of the javascript quoting.
Yes, this does create HTML that is strictly invalid. However, it is a valid technique, and all modern browsers support it.
If it was my, I'd probably go with my first suggestion, and ensure the values are HTML-encoded and have single-quotes escaped.
Declare separate functions in the <head> section and invoke those in your onClick method. If you have lots you could use a naming scheme that numbers them, or pass an integer in in your onClicks and have a big fat switch statement in the function.
Any good templating engine worth its salt will have an "escape quotes" function. Ours (also home-grown, where I work) also has a function to escape quotes for javascript. In both cases, the template variable is then just appended with _esc or _js_esc, depending on which you want. You should never output user-generated content to a browser that hasn't been escaped, IMHO.
I have faced this problem as well. I made a script to convert single quotes into escaped double quotes that won't break the HTML.
function noQuote(text)
{
var newtext = "";
for (var i = 0; i < text.length; i++) {
if (text[i] == "'") {
newtext += "\"";
}
else {
newtext += text[i];
}
}
return newtext;
}
Use the Microsoft Anti-XSS library which includes a JavaScript encode.
First, it would be simpler if the onclick handler was set this way:
<a id="someLinkId"href="#">Select</a>
<script type="text/javascript">
document.getElementById("someLinkId").onClick =
function() {
SelectSurveyItem('<%itemid%>', '<%itemname%>'); return false;
};
</script>
Then itemid and itemname need to be escaped for JavaScript (that is, " becomes \", etc.).
If you are using Java on the server side, you might take a look at the class StringEscapeUtils from jakarta's common-lang. Otherwise, it should not take too long to write your own 'escapeJavascript' method.
Is the answers here that you can't escape quotes using JavaScript and that you need to start with escaped strings.
Therefore. There's no way of JavaScript being able to handle the string 'Marge said "I'd look that was" to Peter' and you need your data be cleaned before offering it to the script?
I faced the same problem, and I solved it in a tricky way. First make global variables, v1, v2, and v3. And in the onclick, send an indicator, 1, 2, or 3 and in the function check for 1, 2, 3 to put the v1, v2, and v3 like:
onclick="myfun(1)"
onclick="myfun(2)"
onclick="myfun(3)"
function myfun(var)
{
if (var ==1)
alert(v1);
if (var ==2)
alert(v2);
if (var ==3)
alert(v3);
}

Categories

Resources