WKWebView OC和JS交互

来源:互联网 发布:微机室上网控制软件 编辑:程序博客网 时间:2024/05/15 04:51

网页很简单,只有一个按钮,点击按钮会触发一个方法,在事件的方法中通过调用 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>

代码实现,通过设置 WKWebViewConfigurationaddScriptMessageHandler: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);}
原创粉丝点击