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;"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With