Xamarin – WebView Calling C# Code From JS

I’m writing this post to document how can we trigger c# code from javascript in (Android & iOS) WebView applications, each different platform has a different way for handling this scenario as following:

Scenario:

We have a hybrid app that needs to mark  page as favourite a link is clicked inside a WebView.

iOS:

We need to add url handler so for e.g. assume we have a page we need to mark this page as favourite from JS will be calling a url like this one “myapp://favourite?pageId=1,value=true” and this url will be handled in C# as below sample:

Android:

We need to create a C# class that will be called from javascript and it needs to inherit from Java.Lang.Object and implement Java.Lang.IRunnable as below:

After this we need to add this class to the WebView:

Finally we can call this function from javascript:

JS

HTML

One thought on “Xamarin – WebView Calling C# Code From JS

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s