iOS从UIWebView检索javascript变量 [英] iOS retrieving javascript variables from UIWebView

查看:92
本文介绍了iOS从UIWebView检索javascript变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个html文件,其中包含< div >并且我正在加载到UIWebView中,我需要知道div中有多少行文本,所以我可以用javascript检查:

I have an html file that has a <div> and that I am loading into a UIWebView and I need to know how many lines of text are in the div, so I can check that with javascript:

<script>
function countLines() {
    var divHeight = document.getElementById('myDiv').offsetHeight;
    var lineHeight = parseInt(document.getElementById('myDiv').style.lineHeight);
    var lines = divHeight / lineHeight;
    alert("Lines: " + lines);
}
</script>

它确实警告变量lines

and it does alert the variable "lines"

在Objective-C中,如何从我的UIWebView中检索此变量,然后在我的代码中使用它?

In Objective-C how can I retrieve this variable from my UIWebView and then use it in my code?

谢谢!

推荐答案

UIWebView方法 stringByEvaluatingJavaScriptFromString:是JavaScript环境的唯一接口。它会计算并返回传递给它的JavaScript表达式值的字符串表示形式。所以,例如:

The UIWebView method stringByEvaluatingJavaScriptFromString: is the sole interface to the JavaScript environment. It evaluates and returns a string representation of the value of a JavaScript expression you pass to it. So, for example:

// simplified expression, no function needed
NSString *expr = @"document.getElementById('myDiv').offsetHeight / document.getElementById('myDiv').style.lineHeight";
// now pass it to the web view and parse the result
int lines = [[self.webView stringByEvaluatingJavaScriptFromString:expr] intValue];

这篇关于iOS从UIWebView检索javascript变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆