iOS从UIWebView中检索JavaScriptvariables
我有一个HTML文件有一个< div
>,我正在加载到一个UIWebView,我需要知道在div中有多less行文本,所以我可以用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>
并确实提醒variables“行”
在Objective-C中,我怎么能从我的UIWebView检索这个variables,然后在我的代码中使用它?
谢谢!
UIWebView方法stringByEvaluatingJavaScriptFromString:
是JavaScript环境的唯一接口。 它评估并返回传递给它的JavaScriptexpression式的值的string表示。 所以,例如:
// 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];
这很容易:
NSString *jsString = @"function countLines() {var divHeight = document.getElementById('myDiv').offsetHeight;var lineHeight = parseInt(document.getElementById('myDiv').style.lineHeight);var lines = divHeight / lineHeight;return lines;};countLines();"; NSString *responseString = [MywebView stringByEvaluatingJavaScriptFromString:jsString];
你应该在responseStringvariables中有值,你可以从NSString转换为数字:-)