Cannot read property 'messageHandlers' of undefined

拥有回忆 提交于 2021-01-27 05:57:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!