網頁很簡單,只有一個按鈕,點擊按鈕會觸發一個方法,在事件的方法中通過調用 window.webkit.messageHandlers.NativeModel.postMessage({name: 'zhangyutang', age: 12});
把消息發送給OC。OC中需要注入相同名稱的model:NativeModel
。
網頁代碼如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>html5page-oc</title>
<script>
function btn1Click() {
window.webkit.messageHandlers.NativeModel.postMessage({name: 'zhangyutang', age: 12});
alert("after call");
}
</script>
</head>
<body>
<input type="button" value="button c" onclick="btn1Click()">
</body>
</html>
代碼實現,通過設置 WKWebViewConfiguration
的 addScriptMessageHandler:name
來設置JS事件的接收處理器,這邊設置爲當前對象self
,這裏的name需要設置爲JS中的調用的Model:NativeModel
。
WKWebViewConfiguration* config = [[WKWebViewConfiguration alloc] init];
config.userContentController = [WKUserContentController new];
[config.userContentController addScriptMessageHandler:self name:@"NativeModel"];
_webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
_webView.translatesAutoresizingMaskIntoConstraints = NO;
_webView.backgroundColor = [UIColor whiteColor];
_webView.UIDelegate = self;
_webView.navigationDelegate = self;
[self.view addSubview:_webView];
實現 WKScriptMessageHandler
的回調方法 userContentController:didReceiveScriptMessage
,在這邊處理JS的方法調用。
#pragma mark - ......::::::: WKScriptMessageHandler :::::::......
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
id body = message.body;
NSLog(@"=== %@", body);
}