Junfeng Li
Junfeng Li

Reputation: 67

iOS stringByEvaluatingJavaScriptFromString is not working in a simple code

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。

Upvotes: 0

Views: 2991

Answers (2)

Martin R
Martin R

Reputation: 539765

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.

Upvotes: 4

Ievgenii
Ievgenii

Reputation: 189

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

Upvotes: -1

Related Questions