2

We are trying to see what is the best option to send some signal To iOS WKWebView from Angular 6, HTML5 project.

Any sample example would be really great.

What we are tyring to do is: we have one button on Angular web page, on click of which it should notify iOS to perform some action. We load Angular page in iOS WKWebView.

With reference to Angular 5 and native IOS/Android communication, it is not very clear. It would be great if there are any samples available from both ios and angular side.

SHN
  • 785
  • 7
  • 23
NILESH
  • 55
  • 10

1 Answers1

3

Apple provides a mechanism in WebKit to post-messages from your HTML to native:

In your HTML page, call:

window.webkit.messageHandlers.messageHandler.postMessage("Pass your data here...");

where, messageHandler is the name of the message received in your iOS code. "Pass your data here..." is the data passed to iOS via messageHandler message.

In your iOS code:

Add a message handler using WKUserContentController's add(_:name:) method like below:

webView.configuration.userContentController.add(self, name: "messageHandler")

Finally, in your ViewController code implement WKScriptMessageHandler's userContentController:didReceiveScriptMessage: method like:

func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
     if message.name == "messageHandler" {
          // Your Message handler code goes here...            
     }

As per Apple documentation of the add(_:name:) method:

Adding a script message handler with name name causes the JavaScript function window.webkit.messageHandlers.name.postMessage(messageBody) to be defined in all frames in all web views that use the user content controller.

Apple Documentation link

SHN
  • 785
  • 7
  • 23
  • in angular 8, using window in component.ts file gave error, in html file used `` and it works – Prem G Apr 13 '22 at 07:06