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: https://gist.github.com/abdomohamed/c2dc805a2e72706227b2

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: https://gist.github.com/abdomohamed/4aa4257e810cb9be9366 After this we need to add this class to the WebView: https://gist.github.com/abdomohamed/2699e6430a5c0d263f92 Finally we can call this function from javascript:

JS

https://gist.github.com/abdomohamed/dc4b05ccac85acaffee3

HTML

https://gist.github.com/abdomohamed/f8e84a53275f478ba357