简体   繁体   English

iOS stringByEvaluatingJavaScriptFromString无法在简单代码中运行

[英]iOS stringByEvaluatingJavaScriptFromString is not working in a simple code

I wrote a piece of code about JS: 我写了一段关于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”不等于“ 123”,结果是

str: 

Any help is appreciated。 任何帮助表示赞赏。

Your JavaScript code only defines the function getString , but never calls the function. 您的JavaScript代码仅定义函数getString ,而不会调用该函数。 Therefore the result of evaluating the script is empty. 因此,评估脚本的结果为空。

If you actually call the function in the JavaScript 如果您实际上在JavaScript中调用了该函数

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

you will get the expected result. 您将获得预期的结果。

This method mosf often usage for running java scripts based on current page contents. 这种方法mosf通常用于基于当前页面内容运行Java脚本。 You can see similar question Here 你可以在这里看到类似的问题

But I've found example with definition of java script here 但我发现例如用Java脚本的定义在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM