Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot read property 'messageHandlers' of undefined

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");
}
like image 842
Abbas Torabi Avatar asked Nov 07 '22 20:11

Abbas Torabi


1 Answers

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)
}
like image 156
M Reza Avatar answered Nov 13 '22 02:11

M Reza