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'

3
  • You might find some parts useful here: stackoverflow.com/a/72503950/4490923 Commented Jan 16, 2023 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. Commented Jan 16, 2023 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. Commented Jan 16, 2023 at 18:15

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.