iOS中WKWebView与JS交互(WebKit)

一、iOS代码

- (void)dealloc {
    //注意这里不能漏写
    [self.webView.configuration.userContentController removeAllUserScripts];
}

- (void)setupWebView {
    self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:self.webView];
    
    NSURL *url = [NSURL URLWithString:@"网址"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
    // share 为 js与oc 保持一致的方法名
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"share"];
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:@"share"]) {
        //TODO message.body
    }
}

- (void)callJs {
[self.webView evaluateJavaScript:@"showResponse('原生调用JS')" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
      if (error) {
          NSLog(@"%@", error);
      } else {
          NSLog(@"%@", response);
      }
 }];
}

二、JS代码

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
            </head>
    <body onload="getLocation()">
            <div>
                    <h1>Native&JavaScript</h1>
            </div>

            <div>
                    <button onclick="callShare()">share</button>
            </div>
             
        <script>
            var callShare = function() {
                    <!--这里对iOS和Android进行一个判别-->
                var ua = navigator.userAgent.toLowerCase();  
                if (/iphone|ipad|ipod/.test(ua)) {
                    <!--如需传给oc参数,如数组,则写法为 "window.webkit.messageHandlers.share.postMessage([1, 'string'])"-->
                    window.webkit.messageHandlers.share.postMessage(null)
                } else if (/android/.test(ua)) {
                    <!--ps: "android"为安卓代码中必须与js保持一致的标识符,可自行定义-->
                    window.android.share()
                }
            }
        </script>
    </body>
</html>

发表评论