2

I've a great problem. I must pass a variable of a javascript function into an objective-C variable. These are my code's parts:

Javascript:

function abc(){
something...
}

Objective-C:

    myLabel.text = [webView stringByEvaluatingJavaScriptFromString:@"documentElement.textContent"];

The javascript code prints to video a number that I want use in my Objective-C code but with this nothing appears, instead using this code:

myLabel.text = [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.textContent"];

It pass the value that I want and the entire code of the javascript function!

Please some advice.... Thanks at all!!!

`

4
  • I guess you need a javascript runtime to embed into the Objective C application... Commented Feb 9, 2012 at 18:08
  • @fortran: The WebView has JavaScript functionality, hence the function he's calling. Commented Feb 9, 2012 at 18:15
  • @T.J.Crowder oh, I thought that "stringByEvaluatingJavaScriptFromString" function was some kind of placeholder name for a real function!!! I couldn't believe such a long name existed ^_^ Commented Feb 9, 2012 at 23:56
  • @fortran: Yeah, it's a doozy. Commented Feb 10, 2012 at 8:32

1 Answer 1

3

You wan to call the function, not just refer to it:

myLabel.text = [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.textContent()"];

the key bit is at the end:

...documentElement.textContent()"];
//                            ^^

Since JavaScript functions are first-class objects, when you do:

x = functionName;

...x receives a reference to the function. In your case, since the UIWebView then coerces it to a string, you end up calling toString on the function, which on most JavaScript implementations gives you the code of the function (although this is not specified by any standard).

To actually call a function, you put parentheses after it (with nothing in them, if there are no arguments you need to pass; or with arguments in them if you do), e.g.:

x = functionName();

Disclosure: I know nothing about iOS development, Objective-C, or UIWebView, but I was able to quickly find the stringByEvaluatingJavaScriptFromString function you were using, and then confirmed via this page that the string after the @ needs to be valid JavaScript code.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.