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文件,导入使用 如何使用?


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

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

6.  navtive调用js方法还有另一种写法,这样可以在任何地方调用js代码,通常放在网页加载完成的代理方法中

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

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值