0

I wrote a piece of code about JS:

NSString *function1 = @"function getString(){return \"123\";}";
NSString *str = [theWebView stringByEvaluatingJavaScriptFromString:function1];
NSLog(@"str: %@", str);

but the "str" is not equal to "123", the result was

str: 

Any help is appreciated。

2
  • There is a typo in your JS : "fuction". And even if that is fixed, the JS only defines the function, but never calls it. Commented Dec 24, 2013 at 7:52
  • you can understand it this way..a function cannot be called automatically. It has to be called. Suppose a script consists of several functions. You will need to explicitly call the function you need. This code doesn't automatically call the function. Commented Dec 24, 2013 at 8:44

2 Answers 2

4

Your JavaScript code only defines the function getString, but never calls the function. Therefore the result of evaluating the script is empty.

If you actually call the function in the JavaScript

NSString *function1 = @"function getString() {return \"123\";} getString()";

you will get the expected result.

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

1 Comment

OK! I did it. Thank you again.
-1

This method mosf often usage for running java scripts based on current page contents. You can see similar question Here

But I've found example with definition of java script here

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.