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;"
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;"
2 Answers
Reset to default 12Well, 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 acplished 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.
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();"];