iOS ---原生与js交互之JavaScriptcore
2020-09-13 本文已影响0人
iOS程序媛ing
1、首先创建一个新类,声明协议,协议遵循<JSExport>协议
#import <Foundation/Foundation.h>
#import <JavaScriptCore/JavaScriptCore.h>
NS_ASSUME_NONNULL_BEGIN
@protocol jsDelegate <JSExport>
- (void)buy;
@end
@interface JsObject : NSObject
@property (nonatomic, assign) id<jsDelegate>delegate;
@end
2、新类的方法与js的方法名一样,在方法中通过代理调用oc方法
#import "JsObject.h"
@implementation JsObject
- (void)buy {
if (self.delegate) {
[self.delegate buy];
}
}
3、在webview的didfinishload方法中将新类注入到js中
- (void)webViewDidFinishLoad:(UIWebView *)webView {
JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
JsObject *js = [[JsObject alloc] init];
js.delegate = self;
context[@"app"] = js;
}