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

Community
  • 1
  • 1
winduptoy
  • 5,366
  • 11
  • 49
  • 67

2 Answers2

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.
Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
  • Could you please help me on this too http://stackoverflow.com/questions/10793698/how-to-make-image-maps-clickable-using-uiwebview-in-iphone – Navnath Memane Jun 27 '12 at 14:11
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();"];
skorulis
  • 4,361
  • 6
  • 32
  • 43