How to set up communication between WebView JavaScript and Xamarin.Forms ApplicationHello Folks 👋!!! Before switching this year to MAUI, let’s summarise not a typical case — communication with JavaScript through WebView. This blog post will show you how to set up JS to XF and XF to JS Commands for Android and iOS.
For our example, we will send some info and show an alert with delay. And react to some HTML button inside Xamarin App.
Prepare WebViewAt First, we need to create a new Custom Control inherited from WebView. Also, it will contain a function to call predefined JS Function and Action, which WebView will call from JS.
https://medium.com/media/3c221dc2a45a4200fd1030bf28c2a8fc/hrefCustomWebView can use it in the following way in code behind Popup or Page.
https://medium.com/media/250492e0cb7d3f7fd79b99ad746bb7e3/hrefJavaScript Binding at iOSFor iOS is enough to create one renderer; let’s name it CustomWebViewRenderer. It should be inherited from WkWebViewRenderer and implement IWKScriptMessageHandler an interface. Also, it should contain a definition of our JS Function InvokeDisplayJSText and registration of our Script Message Handler. Yep, not so much is needed for iOS. Here is the complete renderer code:
https://medium.com/media/8e97727552673ba4d1ae7af20a1f05f3/hrefJavaScript Binding at AndroidFor Android is slightly more complex, but implementation also starts from creating a renderer, let’s give it the same name CustomWebViewRenderer. It should be inherited from WebViewRenderer. Also, it should contain a definition of our JS Function InvokeDisplayJSText (similar to iOS) and registration of our custom JSBridge and JavascriptWebViewClient.
https://medium.com/media/76a06967978266ebc46f84c031e256c4/hrefDefinition of JavascriptWebViewClient is quite simple — it just needs to load defined JS Script when WebView will load page.
https://medium.com/media/bd4fc90fa0120c542bb44e3784773271/hrefDefinition of JSBridge won’t be more complex. We need to export JS Interfaces with the same name defined by our JS Code.
https://medium.com/media/728b9421b93a3171ecd0e441c33aeadd/hrefNow we are loading JS and executing Xamarin Code via JS Bridge 🙃
JavaScript to Xamarin.Forms Two Way Communication Setup was originally published in Nerd For Tech on Medium, where people are continuing the conversation by highlighting and responding to this story.