DEV Community

Filip Němeček
Filip Němeček

Posted on • Updated on

WKWebView: Communicate from web to app with JavaScript

As I have shown, you can easily communicate with website loaded in WKWebView using special method to run JavaScript on the page. You can also do this the other way around and send messages from website to your app.

The first step is to add this protocol: WKScriptMessageHandler. Then add message handler to the WKWebView:

webView.configuration.userContentController.add(self, name: "jsHandler")
Enter fullscreen mode Exit fullscreen mode

The name can be anything you want and you can have multiple of them. The last step on the iOS app part is to implement method to receive messages sent to the handler we just added:

func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if let messageBody = message.body as? String {
        }
}
Enter fullscreen mode Exit fullscreen mode

It is up to you to act on the received message 🙂

Sending messages from website

To receive message, we have to first send it. It is one line of JavaScript code:

window.webkit.messageHandlers.jsHandler.postMessage("Hello from website!");
Enter fullscreen mode Exit fullscreen mode

The jsHandler corresponds to the name we used previously in our Swift code.
And that is all it takes to communicate with your app from WKWebView.

Use cases

Why would you want to send messages from the page? For example you could extend websites menu with specific buttons/links and then open native dialogs or view controllers.

You can also catch specific events with JavaScript event listeners and can react on them.

Is anything not clear? Do you want more information? Ask in the comments and I will do my best to help you. Thanks for reading!

Scan it - wide banner

Top comments (1)

Collapse
 
brendaniwobi profile image
Brendan__iwobi • Edited

Can you actually explain the first step 😐. You can't just say it. You might as well say "Just make it work" 😭