UIWebView stringByEvaluatingJavaScriptFromString

ぐ巨炮叔叔 提交于 2019-11-28 23:15:25

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/4560576/uiwebview-stringbyevaluatingjavascriptfromstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!