且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

无法读取未定义的属性“messageHandlers"

更新时间:1970-01-01 07:56:36

添加测试"消息处理程序后,您需要将其添加到您的webView 的配置中,但是您并没有这样做所以.

After adding the "test" message handler, you need to add it to your webView's configuration, but you are not doing so.

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

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.

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

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