Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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。

share|improve this question
    
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 7:52
    
why never calls it? –  Junfeng Li Dec 24 '13 at 8:09
    
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 8:44

2 Answers 2

up vote 4 down vote accepted

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.

share|improve this answer
    
It works.Thank you very much! –  Junfeng Li Dec 24 '13 at 8:26
    
OK! I did it. Thank you again. –  Junfeng Li Dec 24 '13 at 13:49

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.