使用JavaScriptCore实现OC与JS的交互

为UIWebView添加类别

#import 
#import 

/**
 *  新增UIWebView创建JSContext协议(非必须实现,JSContext构造完成回调)
 */
@protocol JSCWebViewDelegate 
@optional
- (void)webView:(UIWebView *)webView didCreateJavaScriptContext:(JSContext*) ctx;
@end

/**
 *  为UIWebView创建Catergory变量,记录UIWebView当前的JSContext
 */
@interface UIWebView (JavaScriptContext)
@property (nonatomic, readonly) JSContext *javaScriptContext;
@end

#import "UIWebView+JavaScriptContext.h"
#import 

static const char kJavaScriptContext[] = "javaScriptContext";
static NSHashTable *webviewTracker = nil;

@interface UIWebView (JavaScriptCore_private)
- (void) didCreateJavaScriptContext:(JSContext *)javaScriptContext;
@end

@implementation NSObject (JavaScriptCore)

- (void)webView:(id)unUsed didCreateJavaScriptContext:(JSContext *)ctx forFrame:(id)alsoUnused {
    if (!ctx) {
        return;
    }
    //只有NSObject能收到该回调,收到JSContext之后发往对应的UIWebView
    void(^didCreateJavaScriptContext)() = ^{
        for (UIWebView *webView in webviewTracker) {
            NSString* hash = [NSString stringWithFormat: @"jscWebView_%lud", (unsigned long)webView.hash];
            [webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"var %@ = '%@'",hash,hash]];
            if ([ctx[hash].toString isEqualToString:hash]) {
                [webView didCreateJavaScriptContext:ctx];
                return;
            }
        }
    };
    if ([NSThread isMainThread]) {
        didCreateJavaScriptContext();
    }else{
        dispatch_async(dispatch_get_main_queue(), didCreateJavaScriptContext);
    }
}

@end

@implementation UIWebView (JavaScriptContext)

+ (UIWebView *) allocWithZone:(struct _NSZone *)zone {
    //webviewTracker只是弱引用所有UIWebView,销毁时会自动移除
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        webviewTracker = [NSHashTable weakObjectsHashTable];
    });
    UIWebView *webView = [super allocWithZone:zone];
    [webviewTracker addObject:webView];
    return webView;
}

- (void) didCreateJavaScriptContext:(JSContext *)javaScriptContext {
    //javaScriptContext添加KVO(键值观察)支持
    [self willChangeValueForKey:@"javaScriptContext"];
    objc_setAssociatedObject(self, kJavaScriptContext, javaScriptContext, OBJC_ASSOCIATION_RETAIN);
    [self didChangeValueForKey:@"javaScriptContext"];

    //创建JSContext,通知回调
    if ([self.delegate respondsToSelector:@selector(webView:didCreateJavaScriptContext:)]) {
        id  delegate = (id)self.delegate;
        [delegate webView:self didCreateJavaScriptContext:javaScriptContext];
    }
}

- (JSContext *)javaScriptContext {
    return objc_getAssociatedObject(self, kJavaScriptContext);
}

@end

使用方法

1. OC调用JS

// 在需要调用JS方法的地方的实现下面几句代码便可
     JSContext *jsCtx = self.webView.javaScirptContext;
     JSValue *write = jsCtx[@"write"];// 此处@“write”中的write为JS中需要oc调用的方法
    [write callWithArguments:nil]; // 该方法可传NSArray类型参数,不需要传参的话用nil

2. JS调用OC

// .h文件
// 1)JS调用OC方法,需要在webview中创建代理
#import 
#import 

@protocol JavaScriptObjectiveCDelegate 

-(void)write:(NSString *)string;// 该方法为JS调用的OC方法

@end
// .m文件
// JS调用OC方法时,涉及到模型的注入,模型注入需写在-webViewDidFinishLoad方法中
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    JSContext *ctx = self.webView.javaScriptContext;
    ctx[@"myObj"] = self;// 模型注入
// 异常信息打印
    ctx.exceptionHandler = ^(JSContext *context, JSValue *exceptionValue) {
        context.exception = exceptionValue;
        NSLog(@"异常信息:%@", exceptionValue);
    };
}

// 代理方法实现
#pragma mark - JavaScript ObjectiveC Delegate

- (void)write:(NSString *)string{
}

你可能感兴趣的:(使用JavaScriptCore实现OC与JS的交互)