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"  οnclick="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"  οnclick="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);
}];

 

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章