简体   繁体   English

从Objective-C在iOS Web应用程序中调用Javascript

[英]Calling Javascript in an iOS web app from Objective-C

I am developing a web app that is being displayed in a UIWebView . 我正在开发一个在UIWebView中显示的Web应用程序。 The app is loaded locally, ie, not from a web server. 应用程序在本地加载,即不是从Web服务器加载。 I am communicating from Javascript to ObjC via the shouldStartLoadWithRequest: method in the UIWebViewDelegate protocol. 我通过UIWebViewDelegate协议中的shouldStartLoadWithRequest:方法从Javascript与ObjC进行通信。

The last thing I need is to be able to call Javascript functions from ObjC without any page reloads. 我需要的最后一件事是能够从ObjC调用Javascript函数而不需要任何页面重新加载。 I hope this is possible. 我希望这是可能的。

Well, you can call 好吧,你可以打电话

-[UIWebView stringByEvaluatingJavaScriptFromString:]

whenever you like, not just in response to a delegate method. 随时随地,而不仅仅是响应委托方法。

You can call any javascript function in your webview by simply using the stringByEvaluatingJavaScriptFromString method on your webview after you've loaded the webview: 您可以在加载webview后在webview上使用stringByEvaluatingJavaScriptFromString方法调用webview中的任何javascript函数:

[self.myWebView stringByEvaluatingJavaScriptFromString:@"myJavaScriptFunction(123.0)"];

You don't need to reload the webview to send this message (just don't release the webview before you're done). 您无需重新加载webview即可发送此消息(只是在完成之前不要发布webview)。

Could't you just do this by doing a "loadRequest", and passing it an NSURL with contents like like: 难道你不能通过执行“loadRequest”来执行此操作,并将其传递给NSURL,其内容如下:

javascript:myFunction("MyParameter");

It should call your function, but not reload the page. 它应该调用您的函数,但不能重新加载页面。

One can use JavaScriptCore framework to run JavaScript code from Objective-C. 可以使用JavaScriptCore框架从Objective-C运行JavaScript代码。

#import <JavaScriptCore/JavaScriptCore.h>

...

JSContext *context = [[JSContext alloc] init];
[context evaluateScript: @"function greet(name){ return 'Hello, ' + name; }"];
JSValue *function = context[@"greet"];
JSValue* result = [function callWithArguments:@[@"World"]];
[result toString]; // -> Hello, World

Here is a demo: 这是一个演示:

https://github.com/evgenyneu/ios-javascriptcore-demo https://github.com/evgenyneu/ios-javascriptcore-demo

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

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