首页 > 解决方案 > 使用 Javascript 处理 HTML 和 Swift 之间的交互

问题描述

WKWebView 无法在加载的网页中触发 javascript。

场景:如果用户点击网站上的图片,它应该得到更新。

如果用户单击图像,则使用 javascript 更新网站上的图像。

  1. 在项目中包含 .js 文件
  2. 配置好的 WKWebview
  3. 启用 JavaScript
  4. 在 WKWebview 中添加脚本

JS文件中的函数如:

function captureImage(bucket,fileName){
    window.webkit.messageHandlers.captureImage.postMessage("showCamera")
}

在 Swift 中访问此函数,如:

      webViewPWA.configuration.userContentController.add(self, name: "captureImage")


///This function handles the event generated by javascript
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
         print("Webview Message received: \(message.name) with body: \(message.body)")
        if (message.name == "captureImage"){
            print("\(message.body)")

            let body = message.body
            if let action:String = body as? String {
                switch action {
                case "showCamera":
                    print("camera image triggering, capture image for JS")
                    //take necessary action
                    break
                default:
                    break
                }
            }
        }
        return
    }

提前致谢!

标签: javascripthtmliosswiftprogressive-web-apps

解决方案


在设备上以UIImagePickerControllerDelegate如下方法捕获图片后:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        imagePicker.dismiss(animated: true, completion: nil)
        imageView.image = info[.originalImage] as? UIImage
    }

您可以通过使用在 WKWebView 中运行任何您想要的 JS,evaluateJavaScript()并在 Swift 中获得结果。

webView.evaluateJavaScript("document.getElementById('someElement').innerText") { (response, error) in
    guard error == nil else {
          print("evaluateJavaScript error -- \(String(describing: error))")
          return
        }
        print("evaluateJavaScript response -- \(String(describing: response))")
}

拥有类似于 WebBridge.js 的东西也很好,它提供了与 iOS 中的构建 WKWebView 和他的 android webview 进行通信的功能

在 WebBridge.js 内部,您可以定义:

/* install global handler for WebView to call methods */
    if (!window.WebBridge) {
      window.WebBridge = (function () {
        var actions = []


        return {
          receive: function (actionName, json) {
            if (typeof actions[actionName] !== 'undefined') {
              actions[actionName](json)
            }
          },
          registerActionHandler: function (actionName, method) {
            actions[actionName] = method
          }
        }
      })()
    }

然后从 Swift 文件中,您可以缩小 JS 调用的结构:

self.webView.evaluateJavaScript("WebBridge.receive('yourCustomActionName', '{\"yourRey\": \"yourValue\"}')") { (response, error) in
        guard error == nil else {
          print("evaluateJavaScript error -- \(String(describing: error))")
          return
        }
        print("evaluateJavaScript response -- \(String(describing: response))")
      }

推荐阅读