无法读取未定义的 属性 'messageHandlers'

Cannot read property 'messageHandlers' of undefined

我想将 JavaScript 变量传递给 Swift。 我在 JavaScript 中遇到错误并搜索它,但我没有得到任何结果。 错误是:

TypeError: Cannot read property 'messageHandlers' of undefined

有人可以帮忙吗?

我的代码在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)")
   }
}

在JavaScript中:

click: event => {
window.webkit.messageHandlers.test.postMessage("hi");
}

添加 "test" 消息处理程序后,您需要将其添加到 webView 的配置中,但您没有这样做。

通过将此消息处理程序包含到您的 WKUserContentController 对象中,您的 webView 将定义一个可以在所有框架中调用的新函数 window.webkit.messageHandlers.name.postMessage(messageBody)

尝试将您的 viewDidLoad() 更改为以下内容:

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)
}