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");
}
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With