Extension method to escape variable for javascript? - javascript

public string GetEscapedTitle() { return Title.Replace("'", "\\'").Replace("\"", "\\\""); }
I created the above to deal with issues I ran into when doing this in the view:
<a onclick="AddToMyList('#Model.Title', ...
That seemed to fix the errors I was getting when the Title contained single or double quotes. But this wasn't the only property I had the issue with so I had this brilliant idea to create an extension method like so:
public static string EscapeQuotes(this string s)
{
return s.Replace("'", "\'").Replace("\"", "\\\"");
}
Unfortunately, this put me back to square one and I had the same error I got in the beginning when I used it. So what's the difference?
The only thing I can think of is that maybe with the GetEscapedTitle() method razor encodes it after it's escaped but maybe with the extension method it still somehow gets encoded before the extension method is run? That doesn't make sense to me but it's all I can think of right now for why it wouldn't work. :(
Edit: FYI I also just tried adding the .Replace() calls directly in the razor code and that works perfectly fine. But for some strange reason if I do it in the extension method it won't work.

Related

INPUT_GET doesn't work with some strings?

I'm encountering a situation I can't figure out and passing along a string from javascript to PHP via jquery. Simply put when I have a y+ it doesn't seem to pass from javascript to PHP, but when it says y- it does pass. Here is a code for the HTML.
This happens if I type in any math expression that starts with y+. It also happens if it starts with x+. If I change the equation around in anyways as to the string being passed it works unless it starts with one of those two. I've looked at how input_get works but can't find any limitations on the plus sign, similar to how you have to be careful with things like quotes or . I figure there is something like this which is stopping the string from being passed along.
Javascript side:
function initResults(data) {
document.getElementById("test").innerHTML=data;
}
function init() {
var equation=document.getElementById("username").value;
$.get("test.php",{equation: equation},initResults);
}
PHP side:
$equation=filter_input(INPUT_GET,"equation");
print"$equation from php file";
There are no error messages, it just doesn't pass. Below is two screenshots first where it works, the other where it doesn't. I've typed in multiple examples on what works and what doesn't work which I included in the third screenshot. Thanks!

jQuery string escape onclick='deleteRow(item"+count+")' how to quote around item and count

I don't even know how to ask this question correctly, I tried to put quotes around a part of my string however it always break.
I am creating html dynamically and I am encountering error when I try to do this:
onclick='deleteRow("item"+count+"")'
I am trying to pass item1 as a string to a deleteRow function however best I could do is pass it like this deleteRow(item1) with no quotes. I am not sure how to escape them so that they would show.
This line of code is generated inside my JavaScript file.
I would recommend to use jQuery event handlers instead of inline one..
But in this case the below should do it
"onclick='deleteRow(\"item"+count + "\")'"

Escaping single quote from an MVC 3 Razor View variable

I have a variable within item.Name that contains the string "It's Tuesday!".
To alleviate javascript errors, in the c# controller I have already escaped this single quote.
On the webpage, it appears like this "It\'s Tuesday!".
This at least prevents any javascript errors, however, I do not want the actual string displayed to contain the backslash that has escaped it.
How might I be able to revert the escaping once the javascript errors have already been taken care of? This feels like a rather simple problem, but I am a bit unfamiliar with MVC 3. Any hint is much appreciated! My searching did not find me any example specific to this.
An example of my code in the Razor View:
#foreach (var item in Model)
{
#Html.DisplayFor(modelItem => item.Name) // item.Name = "It\'s Tuesday!"
}
Create an extension method you can use or simply encode directly. I would not encode prior to the view getting it unless you have a separate property in your viewmodel meant for this (not a bad idea()
This is not tested but something along these lines
public static class HtmlExtensions
{
public static IHtmlString JavaScriptEncode(this HtmlHelper html, string item)
{
return new HtmlString(HttpUtility.JavaScriptStringEncode(item));
}
}
You can then just call #Html.JavaScriptEncode(yourProperty) from the view or simply reference your encoded property name.
The following can be used to prevent encoding of the output again. This does however rely on you properly dealing with it yourself.
MVCHTMLString
#MvcHtmlString.Create(yourString)
I prefer to make my views dumb. Therefore, I'd have a property called something like 'Display' or 'DisplayName' which handled the escaping for the view.

escape() doesn't seem to work consistently?

using javascript, I generate HTML code, for example adding an function which starts by clicking a link, like:
$('#myDiv').append('click');
So start() should be called if somebody hits the link (click).
TERM could contain a single word, like world or moody's, the generated HTML code would look like:
click
OR
click
As you can see, the 2nd example will not work. So i decided to "escape" the TERM, like so:
$('#myDiv').append('click');
Looking at the HTML source-code using firebug, is see, that the following code was generated:
click
Thats works fine, until I really click the link - so the browser (here firefox) seams to interpret the %27 and tries to fire start('moody's');
Is there a way to escape the term persistent without interpreting the %27 until the term is handled in JS? Is there an other solution instead of using regular expressions to change ' to \'?
Don't try to generate inline JavaScript. That way lies too much pain and maintenance hell. (If you were to go down that route, then you would escape characters in JavaScript strings with \).
Use standard event binding routines instead.
Assuming that $ is jQuery, and not one of the many other libraries that use that unhelpful variable name:
$('#myDiv').append(
$('<a>').append("click").attr('href', 'A sensible fallback').click(function (e) {
alert(TERM); // Because I don't have the function you were calling
e.preventDefault();
})
);
See also http://jsfiddle.net/TudEw/
escape() is used for url-encoding stuff, not for making it possible to put in a string literal. Your code is seriously flawed for several reasons.
If you want an onclick event, use an onclick event. Do not try to "inject" javascript code with your markup. If you have the "string" in a variable, you should never need to substitute anything in it unless you are generating urls or other restricted terms.
var element = $('<span>click</span>');
element.bind('click', function () { start(TERM); });
$('#myDiv').append(element);
If you don't know what this does, then go back to basic and learn what events and function references in javascript means.
That escape() function is for escaping url's for passing over a network, not strings. I don't know that there's a built-in function to escape strings for JavaScript, but you can try this one I found online: http://www.willstrohl.com/Blog/EntryId/67/HOW-TO-Escape-Single-Quotes-for-JavaScript-Strings.
Usage: EscapeSingleQuotes(strString)
Edit: Just noticed your note about regular expressions. This solution does use regular expressions, but I think there's nothing wrong with that :-)

How do I relate a UIWebView javascript exception's sourceId to a source file?

Short question: What does an exception's "sourceID" refer to, and how can I link it to the relevant source string/file?
Longer story:
I am running Javascript code in an iPhone native app through [UIWebView stringByEvaluatingJavaScriptFromString:]. To help development, and later check user-provided code, I use the following function to safely run any code:
// Inside #implementation MyJS
- (NSString *)runJS:(NSString *)js {
// Do some escaping on 'js' to make it look like a string literal.
js = escape(js);
NSString *result =
[webView stringByEvaluatingJavaScriptFromString:
[NSString stringWithFormat:#"try { JSON.stringify(eval(\"%#\")); } except (e) { JSON.stringify(e); }", js]
];
return result;
}
If all goes well, [MyJS runJS:js] runs fine and returns a JSON string containing the result of the evaluation of the last statement in the 'js' code.
Now if bad things happen during the evaluation, I get a JSONified exception object. For example, in case of a syntax error in the 'js' code, I get something like this:
{"message":"Parse error","line":1,"sourceId":26121296}
Which is already quite useful to track problems...
However, as I run multiple strings through runJS:, I would like to be able to pinpoint which one caused the exception (because a runtime error could come from a function that was created in a previous javascript code string). This "sourceId" property looks interesting, but I cannot find what it points to. It looks like a pointer address (similar value as pointers to other objects), but it doesn't match with any of the strings I've passed to the evaluator. How can I make this link?
For bonus points: Is there any documentation available about the UIWebView-specific javascript environment, like this exception object? The Safari Web Content Guide is nice, but doesn't go into this kind of details.
Worst-case solution:
Inside each js string being evaluated, add some code that throws an exception, catches it, extracts the sourceId and somehow exposes it so that the runJS: method can keep a record of which sourceId goes with which string.
(Hopefully someone will find a better way and help bury this ugly answer!)

Categories

Resources