Javascript UIWebView stringByEvaluatingJavaScriptFromString

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4560576/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:57:05  来源:igfitidea点击:

UIWebView stringByEvaluatingJavaScriptFromString

javascriptiphoneuiwebviewuiwebviewdelegate

提问by TomH

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

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

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

但是当调用该方法时, someHTML 为零,而 allHTML 包含 web 视图中 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)

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

Any suggestions?

有什么建议?

More info:

更多信息:

FWIW, result in each of the following is also nil

FWIW,导致以下每个也是零

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

回答by TomH

Changing

改变

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

to

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

(added the .innerHTML)

(添加了 .innerHTML)

makes all the difference in the world . . .

使世界变得不同。. .