WKWebView调用js

直接调用js的changeHead()方法:

webView.evaluateJavaScript("changeHead()") { (any, error) in            
  if (error != nil) {
      print(error)
  }else{
      print(any)
  }
}

//或者弹出alert
webView.evaluateJavaScript("alert('webview加载完成')", completionHandler: nil)

js调用App,传递参数等

WKWebView初始化时候配置WKWebViewConfiguration参数,方法注入可以是多个:

let webConfig = WKWebViewConfiguration()
webConfig.userContentController = WKUserContentController()
//可以添加若干个。 `self`需要实现`WKScriptMessageHandler`方法
webConfig.userContentController.add(self , name: "Native")
webConfig.userContentController.add(self , name: "callbackHandle")
webConfig.userContentController.add(self , name: "callbackHandle2")


let wkwebView = WKWebView.init(frame: self.view.frame, configuration: webConfig)
self.view.addSubview(wkwebView);
self.wkwebView = wkwebView
   
let htmlPath = Bundle.main.path(forResource: "wkWebPage", ofType: "html", inDirectory: "jsCoreDir");
//wkwebView.navigationDelegate = self
wkwebView.uiDelegate = self
wkwebView.load(URLRequest.init(url: URL.init(fileURLWithPath: htmlPath!)))

对应WKScriptMessageHandler需要实现的方法,对应app事件的响应:

extension WKSwiftCallJS_Controller:WKScriptMessageHandler{
    
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        
        print(message.name)                
        switch message.name {
        case "Native":                        
            //callMobile('Native','dosomeThing',{'message':'你好么'})
            print(message.body)  //{'handlerInterface':handlerInterface,'function':handlerMethod,'parameters': parameters}           
            break;            
        case "callbackHandle":            
            //webkit.messageHandlers.callbackHandle.postMessage("Hello World")
            print(message.body) //Hello World            
        case "callbackHandle2":
            //webkit.messageHandlers.callbackHandle2.postMessage({key: "Hello", value: "World"})        
            print(message.body) // {  key = Hello; value = World; }
            break;
        default:
            break
        }
    }
}

js调用的方法为:

<script>
     //js调用APP-传单个参数
    function callNativeApp(){
     try{
         webkit.messageHandlers.callbackHandle.postMessage("Hello World")
     }catch(error){
         console.error('The native context not exist ')
     }
    }
    //js调用APP-传多个参数
    function callNativeApp2(){
      try{
          webkit.messageHandlers.callbackHandle2.postMessage({key: "Hello", value: "World"})
      }catch(error){
          console.error('The native context not exist ')
      }
    }        
    //APP调用js
    function changeHead(){
      document.querySelector('h1').style.color = "red"
    }
</script>

此外,为了保证iOS、Android兼容性,推荐使用狐神的做法http://www.skyfox.org/javascript-ios-navive-message.html

<script type="text/javascript">              
     function callMobile(handlerInterface,handlerMethod,parameters){
          //handlerInterface由iOS addScriptMessageHandler与andorid addJavascriptInterface 代码注入而来。
         var dic = {'handlerInterface':handlerInterface,'function':handlerMethod,'parameters': parameters};

         if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)){
             window.webkit.messageHandlers[handlerInterface].postMessage(dic);
         }else{
             //安卓传输不了js json对象
             window[handlerInterface][handlerMethod](JSON.stringify(dic));
         }
     }
     function callMobileNative(handlerMethod,parameters){
             callMobile("Native",handlerMethod,parameters);
     }
</script>