问题
I want to pass JavaScript variable to Swift. I get an error in JavaScript & search for that but I didn't get any result. The error is:
TypeError: Cannot read property 'messageHandlers' of undefined
Any one can help?
My code in Xcode:
import UIKit
import WebKit
class ViewController: UIViewController,WKScriptMessageHandler,WKNavigationDelegate {
var webView = WKWebView()
override func viewDidLoad() {
super.viewDidLoad()
webView.frame = view.bounds
webView.navigationDelegate = self
let url = URL(string: "MyUrl")!
let urlRequest = URLRequest(url: url)
webView.load(urlRequest)
webView.autoresizingMask = [.flexibleWidth,.flexibleHeight]
view.addSubview(webView)
let userContentController = WKUserContentController()
userContentController.add(self, name: "test")
}
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
print("Name: \(message.name)")
print("Body: \(message.body as! String)")
}
}
And in JavaScript:
click: event => {
window.webkit.messageHandlers.test.postMessage("hi");
}
回答1:
After adding the "test" message handler, you need to add it to your webView
's configuration, but you are not doing so.
By including this message handler into your WKUserContentController
object, your webView will define a new function window.webkit.messageHandlers.name.postMessage(messageBody)
that can be called in all frames.
Try changing your viewDidLoad()
to the following:
override func viewDidLoad() {
super.viewDidLoad()
let config = WKWebViewConfiguration()
let userContentController = WKUserContentController()
userContentController.add(self, name: "test")
config.userContentController = userContentController
webView = WKWebView(frame: view.bounds, configuration: config) // Create webView with the configuration
webView.navigationDelegate = self
let url = URL(string: "MyUrl")!
let urlRequest = URLRequest(url: url)
webView.load(urlRequest)
webView.autoresizingMask = [.flexibleWidth,.flexibleHeight]
view.addSubview(webView)
}
来源:https://stackoverflow.com/questions/54745833/cannot-read-property-messagehandlers-of-undefined