import UIKit
import WebKit
class ViewController: UIViewController, WKScriptMessageHandler {
lazy var webView: WKWebView = {
let webCfg:WKWebViewConfiguration = WKWebViewConfiguration()
// Setup WKUserContentController instance for injecting user script
var userController:WKUserContentController = WKUserContentController()
// Add a script message handler for receiving "buttonClicked" event notifications posted from the JS document using window.webkit.messageHandlers.postMessageListener.postMessage(JSON.stringify({data})) script message
userController.add(self, name: "nativeListener")
// Configure the WKWebViewConfiguration instance with the WKUserContentController
webCfg.userContentController = userController;
let webView = WKWebView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height), configuration: webCfg)
return webView
}()
override func viewDidLoad() {
super.viewDidLoad()
webView.configuration.preferences.javaScriptEnabled = true
self.view.addSubview(webView)
let urlToLoad = URL(string: "your_url_string")
// Do any additional setup after loading the view.
webView.load(URLRequest(url:urlToLoad!))
}
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if message.name == "nativeListener" {
print(message.body) // prints the data that is sent from javascript
}
}
}
let preferences = WKPreferences()
preferences.javaScriptEnabled = true
let configuration = WKWebViewConfiguration()
configuration.preferences = preferences
// Here I am guessing that the Frame of the WebView is the entire Screen
let webView = WKWebView(frame: view.frame, configuration: configuration)
configuration.userContentController.add(self, name: "postMessageListener")
符合方案WKScriptMessageHandler
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if message.name == "postMessageListener" {
// Manage your Data
}
}
2条答案
按热度按时间kgsdhlau1#
使用
postMessage
处理程序将数据从WKWebview's
网页发送到本地代码,2o7dmzc52#
有关简单的解释,您可以查看这篇文章:
https://medium.com/@hoishing/using-javascript-with-wkwebview-64f94153ad0
如果你想要更深入的解释,你可以检查这另一篇文章:
https://dev.to/gualtierofr/wkwebview-and-javascript-interaction-1pbl
在这两篇文章中,他们都提到了如何从Swift触发Javascript函数以及如何接收Javascript消息
无论如何,如果你在JavaScript中执行这个函数:
您必须通过以下方式在Swift中监听名称
postMessageListener
:设置WKWebView
符合方案
WKScriptMessageHandler