最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Passing Javascript Variable to Objective-C - Stack Overflow

programmeradmin3浏览0评论

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

Share Improve this question edited May 23, 2017 at 11:59 CommunityBot 11 silver badge asked Nov 16, 2010 at 3:42 371273371273 5,43611 gold badges50 silver badges68 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 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 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();"];
发布评论

评论列表(0)

  1. 暂无评论