javascript - 使用 Javascript 处理 HTML 和 Swift 之间的交互
问题描述
WKWebView 无法在加载的网页中触发 javascript。
场景:如果用户点击网站上的图片,它应该得到更新。
如果用户单击图像,则使用 javascript 更新网站上的图像。
- 在项目中包含 .js 文件
- 配置好的 WKWebview
- 启用 JavaScript
- 在 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
}
提前致谢!
解决方案
在设备上以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))")
}
推荐阅读
- go - 对普罗米修斯的理解
- ffmpeg - 使用 ffmpeg 直播到 Youtube
- c# - 在 Foreach 循环中获取的数据集/JSON 非常慢,看起来不像是数据库调用的问题
- maven - apache spark中的阴影hadoop
- wordpress - 如何从永久链接中删除“index.php”[作曲家上的 WordPress]
- ios - 错误域 = PlugInKit 代码 = 13 “查询已取消” UserInfo = {NSLocalizedDescription = 查询已取消} 与 Objective C Xcode 9.3 iOS 11
- jenkins - 詹金斯的声纳扫描仪问题
- angular - 无法在角度 6 的 ng2-smart-table 中获取删除事件
- linkedin - 如何在 android 设备的移动linkedin 应用程序中开始一个新段落?
- java - 如何将 API 访问信息输出到记录器文件中?