Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Javascript Variable to Objective-C

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

like image 359
winduptoy Avatar asked Nov 16 '10 03:11

winduptoy


1 Answers

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.
like image 68
Jacob Relkin Avatar answered Sep 22 '22 08:09

Jacob Relkin