2

When sending a message through Javascript to iOS, I encountered this error message that I can't find any information online: "Can only call UserMessageHandler.postMessage on instances of UserMessageHandler".

I am using a webview to render a webpage on iOS.

I tried adding the same script from native code and I was able to receive the message. However, the same script shows the above error if I deploy it on the web site.

let scriptSource = "window.webkit.messageHandlers.jsHandler.postMessage({command: 'command goes here'});"
let userScript = WKUserScript(source: scriptSource, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
userContentController.addUserScript(userScript)

on the web end, I used the following code

key: "onExit",
                    value: function() {
                        var t = function() {
                            try {
                                return window.webkit.messageHandlers.jsHandler.postMessage || null
                            } catch (t) {
                                return null
                            }
                        }();
                        if (t)
                            try {
                                t({
                                    command: "command goes here"
                                }), console.log("window.webkit.messageHandlers.jsHandler.postMessage called successfully")
                            } catch (t) {
                                console.log("error thrown when calling window.webkit.messageHandlers.jsHandler.postMessage - " + (t || {}).message)
                            }
                        else
                            console.log("window.webkit.messageHandlers.jsHandler.postMessage not found!")
                    }
1
  • What did you find out? Commented Aug 31, 2020 at 22:31

1 Answer 1

3

Explicit bind this will resolve the error:

window.webkit.messageHandlers.jsHandler.postMessage.bind(window.webkit.messageHandlers.jsHandler)
Sign up to request clarification or add additional context in comments.

Comments

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.