Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIWebView stringByEvaluatingJavaScriptFromString

I'm stuck on getting some pretty basic JS to run in my UIWebView. In the web view's delegate, I have :

- (void)webViewDidFinishLoad:(UIWebView *)wView {
    NSString *someHTML = [wView stringByEvaluatingJavaScriptFromString:@"document.getElementsByClassName('box')[0]"];   
    NSString *allHTML = [wView stringByEvaluatingJavaScriptFromString:@"document.body.innerHTML"];
    NSLog(@"someHTML: %@", someHTML);
    NSLog(@"allHTML: %@", allHTML);
}

but when the method is invoked, someHTML is nil while allHTML contains the entire body of the HTML in the webview.

I've run the JS in the Safari JS console and it works just fine (it finds a div of class 'box' so I know that its in the HTML)

Any suggestions?

More info:

FWIW, result in each of the following is also nil

NSString *result = [self.webView stringByEvaluatingJavaScriptFromString: @"document"];
NSLog (@"1. result: %@", result); //should log the document object?

result = [self.webView stringByEvaluatingJavaScriptFromString: @"document.body"];
NSLog (@"2. result: %@", result); //should log the document body

result = [self.webView stringByEvaluatingJavaScriptFromString: @"document.body.getElementsByClassName"];
NSLog (@"3. result: %@", result); //should log a function

result = [self.webView stringByEvaluatingJavaScriptFromString: @"document.body.getElementsByClassName('box')[0]"];
NSLog (@"4. result: %@", result); //should log the node
like image 226
TomH Avatar asked Dec 30 '10 06:12

TomH


1 Answers

Changing

NSString *someHTML = [wView stringByEvaluatingJavaScriptFromString:@"document.getElementsByClassName('box')[0]"];   

to

NSString *someHTML = [wView stringByEvaluatingJavaScriptFromString:@"document.getElementsByClassName('box')[0].innerHTML;"];   

(added the .innerHTML)

makes all the difference in the world . . .

like image 123
TomH Avatar answered Nov 04 '22 03:11

TomH