美文网首页
OC与JS交互

OC与JS交互

作者: 辛乐 | 来源:发表于2018-07-20 17:47 被阅读55次

1.OC重写JS里边的方法事件
JS回调OC的原生方法

1.uiwebView

导入系统的处理JS文件

import <JavaScriptCore/JavaScriptCore.h>

//设置JS的上下文属性
@property (strong, nonatomic) JSContext *context;

 NSString *filePath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
 NSString *htmlStr = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
  [self.webView loadHTMLString:htmlStr baseURL:[NSURL URLWithString:[NSString stringWithFormat:@"file://%@",filePath]]];
    [self.view addSubview:webView];

//1.获取JS的上下文    
self.context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
//2.0声明回调
self.context.exceptionHandler = ^(JSContext *context, JSValue *exceptionValue){
        context.exception = exceptionValue;
    };
//3.0重写html中的自定义方法@"goToApp"为方法名
    WEAK_SELF
    self.context[@"goToApp"] = ^(){//重写在html中自定义的方法
        [weakSelf loginAction];
    };
html自定义的方法.png

2.WKWebview

//wkwebview的处理
-(WKWebView *)webView{
    
    if (_webView == nil) {
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        config.preferences.minimumFontSize = 10;
        config.preferences.javaScriptEnabled = YES;//是否支持JS
        config.preferences.javaScriptCanOpenWindowsAutomatically = NO;//不通过用户交互是否可以打开窗口
        _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, CONTENT_SIZEWEIGHT, CONTENT_SIZEHEIGHT) configuration:config];
        [_webView sizeToFit];
        
        //JS调用OC 添加处理脚本(goToApp是与h5约定好的消息名称)
        [config.userContentController addScriptMessageHandler:self name:@"goToApp"];
    }
    return _webView;
}
#pragma mark -- WKScriptMessageHandler

-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    
    NSLog(@"%@",NSStringFromSelector(_cmd));
    NSLog(@"%@",message.body);
    
    if ([message.name isEqualToString:@"goToApp"]) {
       [self loginAction];
    }
}
//还有关键的html的代码按照需要在合适的地方发送~~
 window.webkit.messageHandlers.goToApp.postMessage(['两个参数One', '两个参数Two']);
 window.webkit.messageHandlers.goToApp.postMessage('顺便传了个参数');

2.OC中直接执行JS方法

webVidew的方法
- (nullable NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script;
WKWebview的方法
- (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^ _Nullable)(_Nullable id, NSError * _Nullable error))completionHandler;

相关文章

网友评论

      本文标题:OC与JS交互

      本文链接:https://www.haomeiwen.com/subject/xuyrpftx.html