您知道如何在 Android 中这样做吗?您只需创建一个类,并通过 addJavascriptInterface(Object object, String name) 方法将其实例传递给 WebView。
###一些代码示例,下面介绍一下基本步骤。
@interface MyJSInterface : NSObject
- (void) test;
- (void) testWithParam: (NSString*) param;
- (void) testWithTwoParam: (NSString*) param AndParam2: (NSString*) param2;
- (NSString*) testWithRet;
@end
然后添加该接口到您的 UIWebView 中。
MyJSInterface* interface = [MyJSInterface new];
[self.myWebView addJavascriptInterfaces:interface WithName:@"MyJSTest"];
[interface release];
在 Javascript 中,您可以通过以下简单代码调用 Objective-C 方法。
MyJSTest.test();
MyJSTest.testWithParam("ha:ha");
MyJSTest.testWithTwoParamAndParam2("haha1", "haha2");
var str = MyJSTest.testWithRet();
就这么简单!!! EasyJSWebView 会帮助您完成注入。而且您甚至不需要使用异步式写法来获取返回值!!!
但是,当然,有时我们可能需要使用异步式代码。也支持。您甚至可以从回调函数中获取返回值。
- (void) testWithFuncParam: (EasyJSDataFunction*) param{
NSLog(@"test with func");
NSString* ret = [param executeWithParam:@"blabla:\"bla"];
NSLog(@"Return value from callback: %@", ret);
}
在 Javascript 中,
MyJSTest.testWithFuncParam(function (data){
alert(data); //data would be blabla:"bla
return "some data";
});
注:此项目参考EasyJSWebView进行封装