在上一篇文章中,我總結(jié)了UIWebView
與Native
進(jìn)行交互的三種常用方式. 今天繼續(xù)總結(jié)WKWebView
與Native
進(jìn)行交互的方式.
蘋果在iOS8以后推出了
WebKit
框架,WKWebView
用來負(fù)責(zé)網(wǎng)頁的渲染、展示. 與UIWebView
相比,WKWebView
更加快捷, 內(nèi)存占用更小, 也支持更多的HTML
特性.
一、協(xié)議攔截
(1)絮姆、JSToNative
邏輯: 點(diǎn)擊HTML中的按鈕, 傳遞參數(shù)到Native, Native展示接收到的數(shù)據(jù)
-
實(shí)現(xiàn): JS調(diào)用OC并傳遞參數(shù)
JS代碼:
<div style="margin-top: 20px">
<button onclick = "buttonClick()" style = "font-size: 30px; width: 300px; height: 100px" >
點(diǎn)我~
</button>
</div>
function buttonClick() {
var message = '獲取到html按鈕點(diǎn)擊事件';
clickSuccess(message);
}
function clickSuccess(message) {
var param = 'JS傳遞過來了參數(shù):1234';
JSTransferOC(message, param);
}
function JSTransferOC(message, param) {
var url = 'JSTransferOC://' + message +'?'+ param;
window.location.href = url;
}
- OC代碼:
#import <WebKit/WebKit.h>
#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
//!< 判斷是否是約定好的scheme
if ([navigationAction.request.URL.scheme caseInsensitiveCompare:@"JSTransferOC"] == NSOrderedSame) {
[self presentAlertWithTitle:navigationAction.request.URL.host message:navigationAction.request.URL.query handler:^(UIAlertAction * _Nonnull action) {
decisionHandler(WKNavigationActionPolicyCancel);
}];
} else {
decisionHandler(WKNavigationActionPolicyAllow);
}
//!< 注意這里的 decisionHandler()必須調(diào)用, 否則會(huì)崩潰. 相當(dāng)于UIWebView中的 - shouldStartLoadWithRequest 方法中 返回YES Or NO 是否允許跳轉(zhuǎn)
}
- 原理:
- JS與Native定義好入口函數(shù)
- JSTransferOC()
; - OC遵循
< WKNavigationDelegate >
協(xié)議, 實(shí)現(xiàn)- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
代理方法, 這個(gè)代理方法在webView每次load前都會(huì)調(diào)用; - 在代理方法中, 攔截每次請求, 判斷
request.url.scheme
是否是約定好的scheme
; - 如果是約定好的
scheme
, 那么Native解讀url
, 讀取參數(shù);
- JS與Native定義好入口函數(shù)
(2)崔赌、Native調(diào)用JS, 并傳遞參數(shù)
邏輯: 點(diǎn)擊
Native
登錄按鈕, 登錄成功后, 將數(shù)據(jù)傳遞給JS, JS展示獲取的數(shù)據(jù).-
實(shí)現(xiàn): Native將獲取的數(shù)據(jù)傳遞給JS
JS代碼:
<div style = "font-size: 30px;margin-top: 20px">
回調(diào)數(shù)據(jù)展示:
</div>
<div id = "returnValue" style = "font-size: 30px; border: 1px dotted; height: 100px;margin-top: 20px">
</div>
//!< OC調(diào)用JS, 并回傳給JS參數(shù), JS展示
function OCTransferJS(message, param) {
document.getElementById('returnValue').innerHTML = message + param;
}
- OC代碼:
- (void)login:(UIButton *)sender {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//!< 注意: evaluateJavaScript 只有在webView全部load完成后才能執(zhí)行
[self.webView evaluateJavaScript:[NSString stringWithFormat:@"OCTransferJS('OC調(diào)用JS代碼, 并傳遞參數(shù);', 'OC傳遞來了參數(shù):12345678')"] completionHandler:^(id _Nullable response, NSError * _Nullable error) {
}];
});
}
- 原理:
- JS和Native定義好函數(shù)
OCTransferJS
, 作為入口函數(shù); - Native通過
-evaluateJavaScript: completionHandler:
方法, 執(zhí)行一段JS代碼, 傳遞參數(shù), - JS展示傳遞來的參數(shù);
- JS和Native定義好函數(shù)
二、WKScriptMessageHandler協(xié)議
WKScriptMessageHandler
, 官方釋義為:A class conforming to the WKScriptMessageHandler protocol provides a method for receiving messages from JavaScript running in a webpage
, 為遵循了WKScriptMessageHandler
協(xié)議的類, 提供了一個(gè)用于從webpage
網(wǎng)頁中運(yùn)行的JavaScript
接收消息的方法
(1)木西、JSToNative
邏輯: 點(diǎn)擊HTML中的按鈕, 傳遞參數(shù)到Native, Native接收參數(shù)并展示;
-
實(shí)現(xiàn):JSToNative
JS代碼:
<div style="margin-top: 20px">
<button onclick = "WKScriptMessageHandlerBtnClick()" style = "font-size: 30px; width: 500px; height: 100px" >
WKScriptMessageHandlerBtn
</button>
</div>
//!< 通過WKScriptMessageHandler的方式進(jìn)行交互
function WKScriptMessageHandlerBtnClick() {
var message = '獲取到HTML按鈕點(diǎn)擊事件';
clickComplete(message);
}
function clickComplete(message) {
var param = 'JS傳遞來了參數(shù):12345';
//!< 與webKit進(jìn)行交互時(shí), JS代碼中要這樣調(diào)用
window.webkit.messageHandlers.JSToOC.postMessage(message + ' ' + param);
}
- OC代碼:
#import <WebKit/WebKit.h>
@interface WKWebViewVC ()<WKUIDelegate, WKNavigationDelegate, WKScriptMessageHandler>
//!< 為WKUserContentController添加name為'JSToOC'的 ScriptMessageHandler;
WKUserContentController *userC = [[WKUserContentController alloc] init];
[userC addScriptMessageHandler:self name:@"JSToOC"];
//!< 配置WKWebViewConfiguration;
WKWebViewConfiguration *configuretion = [[WKWebViewConfiguration alloc] init];
configuretion.userContentController = userC;
//!< 使用WKWebViewConfiguration初始化
self.webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:configuretion];
#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
if ([message.name caseInsensitiveCompare:@"JSToOC"] == NSOrderedSame) {
[self presentAlertWithTitle:message.name message:message.body handler:nil];
}
}
- 原理:
- JS和Native約定好入口函數(shù):
JSToOC
; - JS中通過
window.webkit.messageHandlers.JSToOC.postMessage(message + ' ' + param)
的方式, 調(diào)用JSToOC
函數(shù); - OC通過
- addScriptMessageHandler: name:
方法來監(jiān)聽name
為JSToOC
的方法; - OC類遵循
WKScriptMessageHandler
協(xié)議, 并實(shí)現(xiàn)代理方法- userContentController: didReceiveScriptMessage:
, 在代理方法中獲取數(shù)據(jù)message.body
;
- JS和Native約定好入口函數(shù):
注:
- addScriptMessageHandler: name:
會(huì)引起循環(huán)引用, 應(yīng)該在合適的時(shí)間去-removeScriptMessageHandlerForName:
;
(2)、NativeToJS:
和上述方法相同, 都是通過-evaluateJavaScript:completionHandler:
來執(zhí)行一段JS字符串;
三、WKUIDelegate協(xié)議
經(jīng)常有在群里看到朋友抱怨,
WKWebView
中, JS調(diào)用alert()
君珠、confirm()
和prompt()
函數(shù)沒有反應(yīng)。 這是由于WKWebView
的特性,native
必須實(shí)現(xiàn)WKUIDelegate
的三個(gè)代理方法, 才能正常彈出提示框.
(1)赁项、提示框的彈出
邏輯: 點(diǎn)擊
html
中的相應(yīng)按鈕, 在native
中彈出提示框;-
實(shí)現(xiàn): JS通過WKWebView調(diào)用彈窗
JS代碼:
<div id = "returnValue" style = "font-size: 30px; border: 1px dotted; height: 100px;margin-top: 20px">
</div>
<div style="margin-top: 20px">
<button onclick = "alertButtonClick()" style = "font-size: 30px; width: 300px; height: 100px" >
alertButton
</button>
</div>
<div style="margin-top: 20px">
<button onclick = "confirmButtonClick()" style = "font-size: 30px; width: 300px; height: 100px" >
confirmButton
</button>
</div>
<div style="margin-top: 20px">
<button onclick = "promptButtonClick()" style = "font-size: 30px; width: 300px; height: 100px" >
promptButton
</button>
</div>
function alertButtonClick() {
var result = alert('點(diǎn)擊了HTML中的alertButton');
document.getElementById('returnValue').innerHTML = result;
}
function confirmButtonClick() {
var result = confirm('點(diǎn)擊了HTML中的confirmButton');
document.getElementById('returnValue').innerHTML = result;
}
function promptButtonClick() {
var result = prompt('點(diǎn)擊了HTML中的promptButton', '確定');
document.getElementById('returnValue').innerHTML = result;
}
- OC代碼:
- alert:
#pragma mark - WKUIDelegate
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
[self presentAlertWithTitle:@"title" message:message handler:^(UIAlertAction * _Nonnull action) {
completionHandler();
}];
}
- confirm:
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Confirm" message:message preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
completionHandler(NO);
}];
UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"確認(rèn)" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
completionHandler(YES);
}];
[alertController addAction:cancelAction];
[alertController addAction:confirmAction];
[self presentViewController:alertController animated:YES completion:nil];
}
- TextInputPanel:
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:nil preferredStyle:UIAlertControllerStyleAlert];
[alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
textField.placeholder = defaultText;
}];
UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"確認(rèn)" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
completionHandler(alertController.textFields[0].text);
}];
[alertController addAction:confirmAction];
[self presentViewController:alertController animated:YES completion:nil];
}
- 原理:
-
html
中創(chuàng)建各個(gè)彈窗需要的按鈕, 并調(diào)用彈窗的方法; -
native
中實(shí)現(xiàn)WKUIDelegate
中的代理方法, 調(diào)用原生彈窗;
-