Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape NSString for javascript input

I have a string of ASCII characters (created randomly by [NSString stringWithFormat:@"%c", someNumber]), and I want to use that string as input for a javascript method. Something like:

[webView_ stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"my_javascript_method(\"%@\")", myASCIIString]];

How can I escape the NSString? I tried to look into encodeURI and decodeURI, but haven't found any solution yet.

like image 796
Enzo Tran Avatar asked Apr 06 '11 16:04

Enzo Tran


1 Answers

NSJSONSerialization is right there in the corner. To escape NSString to Javascript string literal is hard and could be done wrong easily. (JSONKit use lines of code to deal with it https://github.com/johnezang/JSONKit/blob/82157634ca0ca5b6a4a67a194dd11f15d9b72835/JSONKit.m#L1423)

Below is a little category method to escape the NSString object.

#import "NSString+JavascriptEscape.h"

@implementation NSString (JavascriptEscape)

- (NSString *)stringEscapedForJavasacript {
    // valid JSON object need to be an array or dictionary
    NSArray* arrayForEncoding = @[self];
    NSString* jsonString = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:arrayForEncoding options:0 error:nil] encoding:NSUTF8StringEncoding];

    NSString* escapedString = [jsonString substringWithRange:NSMakeRange(2, jsonString.length - 4)];
    return escapedString;
}

@end

Also, one thing to notice, you've gotta use double quotes in the argument to the javascript function. E.g.,

NSString *javascriptCall = 
    [NSString stringWithFormat:@"MyJavascriptFunction(\"%@\")", escapedString];

[self.webView stringByEvaluatingJavaScriptFromString:javascriptCall];
like image 120
zetachang Avatar answered Sep 29 '22 04:09

zetachang