native与js交互(WKWebView )

1. 创建webView,遵守协议WKScriptMessageHandler

    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    //注入js代码   在html中可以直接调用
    NSString *js = @"function showAlertA() { alert('在载入webview时通过OC注入的JS方法'); }";
    WKUserScript *userScript = [[WKUserScript alloc] initWithSource:js injectionTime:(WKUserScriptInjectionTimeAtDocumentStart) forMainFrameOnly:YES];
    [configuration.userContentController addUserScript:userScript];
    //设置代理,添加监听的key
    [configuration.userContentController addScriptMessageHandler:self name:@"app"];
    
    _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-64) configuration:configuration];
    [self.view addSubview: self.webView];

2. html中调用native方法

<button class="pay-control" type="button"  onclick="showAlertA()">立即下单</button>

注: 在angular中,使用(click)="showAlertA()"事件绑定不起作用


3. 实现WKScriptMessageHandler代理方法,当js调用约定的方法,可在此添加实现。

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    NSLog(@"%@  %@",message.name,message.body);
}

4. html中向native端发送事件,并可以携带数据信息,注意方法名'printSB'、事件的标志'app'、携带的信息'{body: 'SB'}'

  <script>
    function printSB() {
      window.webkit.messageHandlers.app.postMessage({body: 'SB'});
    }
  </script>
<button class="pay-control" type="button"  onclick="printSB()">立即下单</button>

注:当点击按钮,native端控制台会打印出message信息,实现js回调native方法,在angular中,component模板中会屏蔽掉<script>标签,所以可以将上面的js代码放到index.html中实现全局引用;当然也可以单独弄成一个js文件,导入使用(看另一篇文章 http://blog.csdn.net/nb_token/article/details/78337413)。


5. 最后,由于addScriptMessageHandler方法容易循环引用导致内存泄漏,在viewDidDisappear加入

    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"app"];






6.  navtive调用js方法还有一种写法(见另一篇文章:http://blog.csdn.net/nb_token/article/details/62228010),这样可以在任何地方调用js代码,通常放在网页加载完成的代理方法中

NSString *jsStr = [NSString stringWithFormat:@"shareResult('%@','%@','%@')",title,content,url];
[self.webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        NSLog(@"%@----%@",result, error);
}];






猜你喜欢

转载自blog.csdn.net/NB_Token/article/details/78367678