Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

560
Views
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");
}
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

After adding the "test" message handler, you need to add it to your webView , but you're not doing that.

By including this message handler in 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) }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!