5

I've seen how to pass an Objective-C variable to JavaScript right here, passing objective c variable to javascript in ios, but how do I pass a variable from JavaScript to Objective-C when I'm using something like this:

[webView stringByEvaluatingJavaScriptFromString:@"var elems = document.body.getElementsByTagName(\"u\");" "passThisVarToObjC = elems.length;"

0

2 Answers 2

12

Well, this is what we call stringly typed.

Because the return type of stringByEvaluatingJavaScriptFromString: is NSString *, you will either need to stick to using a string or coercing the value into some other (read:more usable) type.

But anyway, stringByEvaluatingJavaScriptFromString: will return the value of a JavaScript variable to you without a problem.

The way this is accomplished is through the use of an anonymous function (which in this case is self-executing):

NSString *numOfElements = [webView stringByEvaluatingJavaScriptFromString:@"(function() {var elems = document.body.getElementsByTagName(\"u\"); return elems.length;})();"];

//do normal stuff with numOfElements like cast to an int or something cool like that.
Sign up to request clarification or add additional context in comments.

1 Comment

Could you please help me on this too stackoverflow.com/questions/10793698/…
3

You need to have a return statement in your javascript. There may be better ways to do it but the following javascript works for me:

    NSString* findLink = @"function f() {var x = document.getElementsByTagName('a');
if(x.length > 0) { return x[0].getAttribute('href');}; return null;} f(); ";

Try using this code:

[webView stringByEvaluatingJavaScriptFromString:@"function f() {var elems =
document.body.getElementsByTagName(\"u\"); return elems.length;}f();"];

Comments

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.