YosiFZ
YosiFZ

Reputation: 7890

Excute JavaScript in my iPhone app

I have this JavaScript function :

function extract(html) {
     return html;
}

And i want to run it from my iPhone app, so i create a UIWebView and add it:

        UIWebView *fullJavaScriptWebView = [[UIWebView alloc] init];
        fullJavaScriptWebView.delegate = self;

        NSURL *fileUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"] isDirectory:NO];

        [fullJavaScriptWebView loadRequest:[NSURLRequest requestWithURL:fileUrl]];

And in the UIWebViewDelegate webViewDidFinishLoad :

NSString *html = [self.javaScriptDic objectForKey:@"html"];
NSString *jsCall = [NSString stringWithFormat:@"extract('%@');",html];
NSString *tmp = [webView stringByEvaluatingJavaScriptFromString:jsCall];

And every time i run it, tmp is null. Any idea what's wrong with this code?

the html is html of website that i download before and it include chars like : ",'.......

Upvotes: 0

Views: 83

Answers (2)

Numeral
Numeral

Reputation: 1405

Load html string into webView:

NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"Untitled" ofType:@"html" inDirectory:nil];
NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil];
    [self.webView loadHTMLString:htmlString baseURL:nil];

Then you can get inner html, make your operations and return result:

- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSString *result = [webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat: @"function f(){ var markup = document.documentElement.innerHTML; return markup;} f();"]];
NSLog(@"result: '%@'", result);
}

Upvotes: 0

Jonathan Naguin
Jonathan Naguin

Reputation: 14766

The html var seems to have problematic characters if you are going to pass it to a Javascript function. Try to scape it first:

-(NSString *)scapeForJS:(NSString *)string {
    string = [string stringByReplacingOccurrencesOfString:@"\\" withString:@"\\\\"];
    string = [string stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    string = [string stringByReplacingOccurrencesOfString:@"\'" withString:@"\\\'"];
    string = [string stringByReplacingOccurrencesOfString:@"\n" withString:@"\\n"];
    string = [string stringByReplacingOccurrencesOfString:@"\r" withString:@"\\r"];
    string = [string stringByReplacingOccurrencesOfString:@"\f" withString:@"\\f"];
    return string;
}

Upvotes: 1

Related Questions