0

I am loading a local html file with this inside <script>

window.webkit.messageHandlers.MyHandler.postMessage("hello");

What changes do i need on my swift file to handle setup this handler?

my current swift file :

struct WebView: UIViewRepresentable {
    var url: URL

    ...

    func makeUIView(context: Context) -> WKWebView {
        // do configuration here

        let view = WKWebView()
        view.navigationDelegate = context.coordinator
        view.load(URLRequest(url: url))

        return view
    }
    ...

Thanks.

Tried this:

    func makeUIView(context: Context) -> WKWebView {
        
        let userController = WKUserContentController()
        userController.add(self, name: "MyHandler")
        let configuration = WKWebViewConfiguration()
        configuration.userContentController = userController
        return WKWebView(frame: frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, idealHeight: 500, maxHeight: .infinity) as! CGRect, configuration: configuration)

but i'm getting error on self: Argument type 'WebView' does not conform to expected type 'WKScriptMessageHandler'

  • You might find some parts useful here: https://stackoverflow.com/a/72503950/4490923 – Asteroid Jan 16 '23 at 16:35
  • I'm implementing mine using `struct WebView: UIViewRepresentable { ... }`, and most of the answers (I've found, so far) start with `class ViewController: UIViewController`. It's really tripping me up (sorry, i am new with swift). I don't know how to transform the swiftui answers to just UIKit. – Gian Gavan Jan 16 '23 at 16:53
  • The function `add(_:name:)` on `WKUserContentController` requires that `self` conforms to `WKScriptMessageHandler`, because you are using it as argument. You could try to conform your `WebView` to the required protocol. – burnsi Jan 16 '23 at 18:15

0 Answers0