JavaScript to Xamarin.Forms Two Way Communication Setup
How to set up communication between WebView JavaScript and Xamarin.Forms Application
Hello 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 WebView
At 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.
CustomWebView can use it in the following way in code behind Popup or Page.
JavaScript Binding at iOS
For 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:
JavaScript Binding at Android
For 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
.
Definition of JavascriptWebViewClient
is quite simple — it just needs to load defined JS Script when WebView will load page.
Definition of JSBridge
won’t be more complex. We need to export JS Interfaces with the same name defined by our JS Code.
Now we are loading JS and executing Xamarin Code via JS Bridge 🙃