UIWebView stringByEvaluatingJavaScriptFromString

TomH picture TomH · Dec 30, 2010 · Viewed 31.5k times · Source

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

Answer

TomH picture TomH · Dec 30, 2010

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 . . .