UIWebView stringByEvaluatingJavaScriptFromString

问题描述:

我坚持要在我的UIWebView中运行一些非常基本的JS。在Web视图的委托中,我有:

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);
}

但是当调用该方法时,someHTML为nil而allHTML包含整个body webview中的HTML。

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

我在Safari JS控制台中运行JS并且它工作得很好(它找到了一个类'box'的div,所以我知道它在HTML中)

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)

有什么建议吗?

更多信息:

FWIW,结果以下各项也是零

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


更改

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

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

(添加.innerHTML)

(added the .innerHTML)

让世界变得与众不同。 。 。

makes all the difference in the world . . .