本文介绍两种方式实现iOS WKWebView和JS交互html
网页很简单,只有一个按钮,点击按钮会触发一个方法,在事件的方法中经过调用 window.webkit.messageHandlers.NativeModel.postMessage({name: 'zhangyutang', age: 12});
把消息发送给Objc。Objc中须要注入相同名称的model:NativeModel
。网页代码以下html5
<!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>
Objc代码中在初始化WKWebView
的时候须要使用initWithFrame:(CGRect)frame configuration:(WKWebViewConfiguration *)configuration
方法来进行初始化。 WKWebViewConfiguration
对象须要使用调用方法 addScriptMessageHandler:name
来设置JS事件的接收处理器,addScriptMessageHandler:name
方法有两个参数:ScriptMessageHandler
参数须要是一个实现WKScriptMessageHandler
了协议的对象;name
参数是H5页面中调用postMessage
方法使用到的注入对象的名称,H5页面和原生的页面交互使用经过该对象才能够成功调用。web
- (WKWebView *)webView { if (!_webView) { 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.navigationDelegate = self; } return _webView; }
MMWebViewController
类实现了实现 WKScriptMessageHandler
协议,重写 userContentController:didReceiveScriptMessage
回调方法 ,在该方法中处理JS的方法调用,关键的代码片断以下。ide
@interface MMWebViewController () <WKScriptMessageHandler> @end @implementation MMWebViewController #pragma mark - ......::::::: WKScriptMessageHandler :::::::...... - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message { id body = message.body; NSLog(@"=== %@", body); } @end
重写UIWebViewDelegate
的回调方法- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
,在该方法中经过判断请求的URL的scheme
来处理特定URL,能够处理原生页面的跳转、原生页面的弹窗等业务逻辑,而后调用decisionHandler(WKNavigationActionPolicyCancel);
告诉WKWebView
不用处理这个请求,这个请求已经让原生处理了。简单的代码片断以下oop
if ([navigationAction.request.URL.scheme isEqualToString:@"plush"]) { [PTLinkUtil handleURLString:navigationAction.request.URL.absoluteString linkType:PTLinkCustomHandler roomID:0]; decisionHandler(WKNavigationActionPolicyCancel); return; } else if ([[navigationAction.request.URL.scheme lowercaseString] isEqualToString:@"lezhua"]) { if ([[navigationAction.request.URL.host lowercaseString] isEqualToString:@"home"]) { NSArray *queryItems = [NSURLComponents componentsWithString:navigationAction.request.URL.absoluteString].queryItems; for (NSInteger i = 0; i < queryItems.count; i++) { NSURLQueryItem *loopItem = queryItems[i]; if ([[loopItem.name lowercaseString] isEqualToString:@"segmentid"]) { [UIUtil showWithSegmentID:[validString(loopItem.value) integerValue]]; } } } decisionHandler(WKNavigationActionPolicyCancel); return; }