15

i'm new using monotouch.

My problem is i want call a javascript function from a monotouch function and javascript function could call a monotouch function too.

I believe that with objective c this problem is possible, but i need making it with monotouch.

Help me please.

any help is thank for advance

user672206
  • 151
  • 1
  • 1
  • 3

3 Answers3

27

To invoke Javascript code running in the UIWebView from your application, use the EvaluateJavascript method, like this:

myView.EvaluateJavaScript ("a = 1;");

To call back into your C# code, the only option is to hook up to the ShouldStartLoad property like this:

myView.ShouldStartLoad = myHandler;

[...]

bool myHandler (UIWebView webView, NSUrlRequest request, UIWebViewNavigationType navType)
{
    // Determine what to do here based on the @request and @navType
} 

You can of course, also use anonymous methods if you want to access local variables easily:

myView.ShouldStartLoad = (webView, request, navType) => {
     // Determine here what to do
}

In the Javascript side, if you want to call back to Mono, you then set the location.href property to a "special" url, like this:

// Javascript code:
location.href = "myapp://action?par1=abc&par2=def"

The information will be available on the request object: request.Url.AbsoluteString

miguel.de.icaza
  • 32,654
  • 6
  • 58
  • 76
  • Thanks, Miguel!! A million times, thanks!! This just answered my question as well... my question is here: http://stackoverflow.com/questions/5404152/shouldstartload-of-custom-uiwebviewdelegate-not-being-called-when-uiwebview-reque. I am busy building a bridging mechanism for two-way communication between javascript and monotouch and have been struggling with implementing ShouldStartLoad delegate. This gave me the info that I needed to get it working. :) :) :) – BruceHill Mar 23 '11 at 15:15
  • Ok, great. I'm trying to override an ajax call. I can replace the PageMethods.Method() with a function which calls a special url like you said, but i need the call to give a response. How can I do that? – Radu Simionescu Oct 22 '13 at 11:16
  • The request.Url.AbsoluteString stays the same for any calls. How to pass "myapp://action?par1=abc&par2=def" with the url – User382 Apr 12 '16 at 20:22
7

I just released MonoTouch JsBridge to make this easier. It allows you to add event listeners and fire events between the native side and the UIWebView. It was inspired by Titanium.

https://github.com/crdeutsch/MonoTouch-JsBridge

cdeutsch
  • 3,847
  • 27
  • 25
0

I haven't tried it in monotouch, but it should be the same as in ObjC:

UIWebView.EvaluateJavascript
David Notario
  • 297
  • 2
  • 9