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。

Junfeng Li
  • 57
  • 1
  • 9
  • There is a typo in your JS : "fuction". And even if that is fixed, the JS only defines the function, but never calls it. – Martin R Dec 24 '13 at 07: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. – mak Dec 24 '13 at 08:44

2 Answers2

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.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
-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

Community
  • 1
  • 1
Ievgenii
  • 189
  • 7