【问题标题】:Handle interaction between HTML and Swift using Javascript使用 Javascript 处理 HTML 和 Swift 之间的交互
【发布时间】:2019-08-20 07:02:26
【问题描述】:

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
    }

提前致谢!

【问题讨论】:

  • 当你点击图片时打印("camera image triggering, capture image for JS") 被执行?
  • 是的,它正在执行。

标签: javascript html ios swift progressive-web-apps


【解决方案1】:

一旦在设备上以UIImagePickerControllerDelegate 方法捕获图片,例如:

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

您可以使用evaluateJavaScript() 在 WKWebView 中运行您想要的任何 JS,并在 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))")
      }

【讨论】:

  • 谢谢尼克这对我有帮助
猜你喜欢
  • 1970-01-01
  • 2015-03-31
  • 1970-01-01
  • 1970-01-01
  • 2018-11-21
  • 1970-01-01
  • 2016-01-15
  • 2011-02-04
  • 1970-01-01
相关资源
最近更新 更多