Escape character removed when using selenium execute_script through python - javascript

I need to have these characters in my string: "'\;
userID = "__\"__\'__\;__"
I am running javascript through python to update the username field:
driver.execute_script("window.document.getElementById('username').value = '%s';" %userID)
Now my problem is that in the end my script becomes:
window.document.getElementById('username').value = '__"__'__\;__';
And this causes errors since I have single quote without escape character. How can I keep the escape character in front of the single quote?

Don't use interpolation. Instead, pass the value as a parameter to execute_script:
driver.execute_script("window.document.getElementById('username').value = arguments[0];",
userID)
The arguments you pass to execute_script after the script are available as arguments[0], arguments[1], etc. on the JavaScript side. (This is not a special Selenium thing but how JavaScript works. The script you give to execute_script is wrapped in a function object and function parameters are available on the arguments object.)
When you pass the value as a parameter like above, Selenium will serialize the Python value to its corresponding JavaScript value on the browser side and it will preserve your string.

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.

Passing a string value from c# file to js file

I am trying to pass a string value from c# file to js file.
If I try to pass an int value, then I can pass it, but I am unable to pass string value.
string value = "abc";
int a=5;
TableCell.Attributes.Add("onclick", "F1("+value +")"); //NOTHING HAPPENS
TableCell.Attributes.Add("onclick", "F1("+a +")"); //Works Perfectly
js file
function F1(value) {
alert(value);
}
Pass string value in quotes ''
Use
TableCell.Attributes.Add("onclick", "F1('"+value +"')");
^ ^
Otherwise it treated as variable. Currently you must be getting error in browser console.
Consider what your HTML will look like.
First version:
onclick="F1(abc)"
Second version:
onclick="F1(5)"
Clearly the second version is passing the value 5. The first version is passing the value of abc - whatever that is, within the context of the Javascript you're executing.
You could quote the string, making sure that you escape quotes etc - I'm assuming that in reality, your value is fetched dynamically from somewhere, and you might not have much control over the content. Hopefully there's something within whatever ASP.NET version you're using that will let you do that, such as HttpUtility.JavaScriptStringEncode.
For example, to get the string abc in your call, you want the attribute to be:
onclick="F1('abc')"
but if to get the string I don't know in your call, you want the attribute to be:
onclick="F1('I don\'t know')"
The key is to look at the generated HTML - pretend you're the browser, and look at the world from its perspective. Once you've worked out what HTML you want to generate, writing the code to do so is often relatively simple.
Try adding single-quotes around the value when building it in your C# string. In your first scenario, the Js is receiving:
F1(abc);
Which it reads as being the variable abc. Try adding single quotes (and it's probably best to use string.format, BTW):
TableCell.Attributes.Add("onclick", string.Format("F1('{0}')", value));
When you use the string, it would produce the JavaScript code F1(abc). That would interpret abc as a variable name, not a string literal.
Add apostrophes around the string to make it a string literal:
TableCell.Attributes.Add("onclick", "F1('" + value + "')");
If the string can contain apostrophes or backslashes, you would need to escape them:
TableCell.Attributes.Add("onclick", "F1('" + value.Replace("\\", "\\\\").Replace("'", "\\'") + "')");
This will take care of escaping any special characters (i.e. quotes, etc...)
TableCell.Attributes.Add("onclick", "F1('"+HttpUtility.JavaScriptStringEncode(value)+"')");
If you're passing a string through the argument, you need either " or ' characters to delimit it. Your variable name is translating to (adb) in the call. ("adb") or ('adb') would be the string value.
That's because it will print
F1(abc)
So it will look for a variable called abc.
You should use
TableCell.Attributes.Add("onclick", "F1(\""+value +"\")");
So the output will be
F1("abc")

Javascript with Special Chartecter

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')"

unterminated string literal in javascript

I have one string in my JSON. the value is To be Reviewed.
I am retrieving this string in my client side using data[i].status syntax. It fetches the correct value but when I send this syntax as paramter it gives unterminated string literal error on client side.
My code is:
onClick=test('"+data[i].product+"','"+data[i].status+"').
How can I send the string value in another function?
thanks in advance.
As you are appending variables you do not need the quotes around them, only the value you are assigning to the onClick parameter. Assuming your test function accepts two parameters, this should work:
onClick="test(data[i].product, data[i].status)"

encodeURIComponent inline on onClick

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)"

Categories

Resources