0

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>

and it does alert the variable "lines"

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

Thankyou!

2 Answers 2

8

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];
Sign up to request clarification or add additional context in comments.

Comments

3

This is easy:

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];

And you should have the value in the responseString variable, which you can convert from a NSString to number :-)

3 Comments

The <script> tags will cause this to fail, and there's no need to define a function just to call it. It could be an IIFE or a simple expression.
You might need to call the function at a custom JavaScript event and that's why I kept it...
@JohnCromartie You are correct about the script tags. Editing to remove them

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.