Bug 23474 - Add support to access C# objects from JavaScript via JavaScriptCore
Summary: Add support to access C# objects from JavaScript via JavaScriptCore
Status: VERIFIED FIXED
Alias: None
Product: iOS
Classification: Xamarin
Component: XI runtime ()
Version: master
Hardware: PC Mac OS
: Normal enhancement
Target Milestone: 8.10
Assignee: Rolf Bjarne Kvinge [MSFT]
URL:
: 32048 ()
Depends on:
Blocks:
 
Reported: 2014-09-29 22:17 UTC by cwaldron
Modified: 2015-07-17 05:01 UTC (History)
8 users (show)

Tags:
Is this bug a regression?: ---
Last known good build:

Notice (2018-05-24): bugzilla.xamarin.com is now in read-only mode.

Please join us on Visual Studio Developer Community and in the Xamarin and Mono organizations on GitHub to continue tracking issues. Bugzilla will remain available for reference in read-only mode. We will continue to work on open Bugzilla bugs, copy them to the new locations as needed for follow-up, and add the new items under Related Links.

Our sincere thanks to everyone who has contributed on this bug tracker over the years. Thanks also for your understanding as we make these adjustments and improvements for the future.


Please create a new report on Developer Community or GitHub with your current version information, steps to reproduce, and relevant error messages or log files if you are hitting an issue that looks similar to this resolved bug and you do not yet see a matching new report.

Related Links:
Status:
VERIFIED FIXED

Description cwaldron 2014-09-29 22:17:28 UTC
According to the documentation, C# code cannot be called directly from JavaScript however you can call Objective C objects directly from JavaScript.  This is made available via the JSExport protocol.  This protocol class is exposed to C# thus it should work since the class is available.

The way it should work is that you inherit this protocol class and decorate the method on the class with the Export attribute that you want exposed as an Objective C method.  Something like this ...

namespace JavaScriptTest
{
    public class JavascriptBridge : JSExport
    {
        public JavascriptBridge() 
        {
        }

        [Export("addContact:")]
        public void AddContact(string data)
        {
            Console.WriteLine("kilroy is here!!!");
        }
    }
}


Then to establish the JavaScript binding you'd do something like this ...

            // get JSContext from UIWebView instance
            JSContext context = new JSContext();

            // enable error logging
            context.ExceptionHandler = new JSContextExceptionHandler((ctx, ex) => {
                Console.WriteLine("WEB JS: {0}", ex);
            });

            // give JS a handle to the JavaScript bridge.
            context[new NSString("myApp")] = JSValue.From(new JavascriptBridge(), context);

            // JavaScript that calls into the JavaScript bridge method 'addContact'.
            string addContactText = "if (myApp.addContact !== undefined) {myApp.addContact('hello world')}";

            // Execute the script.
            context.EvaluateScript(addContactText);
Comment 1 cwaldron 2014-10-04 22:48:58 UTC
You can refer to this article from Big Nerd Ranch to see how JSContext is used in Objective C and download the example:  http://www.bignerdranch.com/blog/javascriptcore-example/
Comment 2 Brendan Zagaeski (Xamarin Team, assistant) 2014-12-02 18:27:01 UTC
Here's a closely related enhancement (about a different limitation with the current bindings for JavaScriptCore) that contains a little bit of potentially useful additional discussion: https://bugzilla.xamarin.com/show_bug.cgi?id=17550.

The original title of this bug was a little confusing when compared to bug 17550, so I reworded it slightly. This bug (bug 23474) is about sending whole C# objects into JavaScript. The Objective-C mechanism for doing that requires defining _new Objective-C protocols_ that extend `JSExport`, and Xamarin does not currently have a way to do that from C#.
Comment 3 Rolf Bjarne Kvinge [MSFT] 2014-12-22 14:38:32 UTC
Looks like we can't register protocols dynamically for JavaScriptCore: http://blog.brandonevans.ca/post/99491153293/dynamically-exporting-objective-c-classes-to
Comment 4 Rolf Bjarne Kvinge [MSFT] 2014-12-23 07:52:51 UTC
Fixed.

maccore/master: b0d8355c0931ad3059066cdb0d37305e0431040e
monotouch/master: ff538393745da3924c9346f3e9f769a7bc91efae

The only catch is that the static registrar must be used.
Comment 5 Rolf Bjarne Kvinge [MSFT] 2014-12-23 07:54:44 UTC
Here is a sample: https://gist.github.com/rolfbjarne/5d3bab08ed88bff9db88
Comment 6 asimk 2015-03-02 08:16:23 UTC
@Rolf, I have checked this issue with the help of Bug description and sample code attached in comment 5. I observed that when I run application  I am getting "JS exception" as shown in Screencast.
Screencast:  http://www.screencast.com/t/w6C65JeQ

After commenting "context.ExceptionHandler" I am getting following error : 
2015-03-02 18:37:50.312 JavaScriptTest[5357:148816] ObjCRuntime.RuntimeException: Detected a protocol (JavaScriptTest.IMyJavaExporter) inheriting from the JSExport protocol while using the dynamic registrar. It is not possible to export protocols to JavaScriptCore dynamically; the static registrar must be used (add '--registrar:static to the additional mtouch arguments in the project's iOS Build options to select the static registrar).

Due to this exception, I am not able to move ahead. Please review the screencast and let us know what additional step we need to follow to verify this issue.

Ide Log: https://gist.github.com/saurabh360/26e8382fa53e34fb0cfe

Environment Info: 
=== Xamarin Studio ===

Version 5.8 (build 1041)
Installation UUID: d6f15b80-470e-4e50-9aba-38a45c556680
Runtime:
	Mono 3.12.0 ((detached/b8f5055)
	GTK+ 2.24.23 (Raleigh theme)

	Package version: 312000077

=== Apple Developer Tools ===

Xcode 6.2 (6770)
Build 6C121

=== Xamarin.iOS ===

Version: 8.9.1.397 (Enterprise Edition)
Hash: 016fd4e
Branch: master
Build date: 2015-02-26 19:15:06-0500

=== Xamarin.Android ===

Version: 5.0.99.288 (Enterprise Edition)
Android SDK: /Users/360logica/Desktop/Anddk/android-sdk-macosx
	Supported Android versions:
		2.3    (API level 10)
		4.0.3  (API level 15)
		4.1    (API level 16)
		4.2    (API level 17)
		4.3    (API level 18)
		4.4    (API level 19)
		4.4.87 (API level 20)
		5.0    (API level 21)
Java SDK: /usr
java version "1.8.0_25"
Java(TM) SE Runtime Environment (build 1.8.0_25-b17)
Java HotSpot(TM) 64-Bit Server VM (build 25.25-b02, mixed mode)

=== Xamarin Android Player ===

Version: Unknown version
Location: /Applications/Xamarin Android Player.app

=== Xamarin.Mac ===

Version: 1.13.1.397 (Enterprise Edition)

=== Build Information ===

Release ID: 508001041
Git revision: fb49f5b17bced266244831c07c28f9fc93915cb1
Build date: 2015-02-27 12:58:53-05
Xamarin addins: e88a2212bb7156a42ad6728b82e99846c3eea817

=== Operating System ===

Mac OS X 10.10.0
Darwin 360Logicas-MacBook-Pro.local 14.0.0 Darwin Kernel Version 14.0.0
    Fri Sep 19 00:26:44 PDT 2014
    root:xnu-2782.1.97~2/RELEASE_X86_64 x86_64
Comment 7 Rolf Bjarne Kvinge [MSFT] 2015-03-02 08:35:35 UTC
@asimk, can you add "--registrar:static" to the additional mtouch arguments in the project's iOS Build options and try again?
Comment 9 michael.prokopchuk 2015-03-02 15:38:36 UTC
I have also tried the sample gist verbatim with the "--registrar:static" option and get the same error:

JS exception: TypeError: undefined is not a function (evaluating 'obj.myFunc ()')

Some debugging I did leaves me to believe the MyJavaExporter instance is seen as an empty object in JS.

// typeof obj;
2015-03-02 15:25:49.763 JSXamarinTest[67469:16727641] object

// typeof obj.myFunc;
2015-03-02 15:25:49.764 JSXamarinTest[67469:16727641] undefined

// Object.keys(obj).length;
2015-03-02 15:25:49.764 JSXamarinTest[67469:16727641] 0

I had some linker errors that went away after changing the iOS build settings to "Link SDK assemblies only", but that did not change the result of evaluating the JS.
Comment 10 Rolf Bjarne Kvinge [MSFT] 2015-03-02 15:47:19 UTC
@Michael, this fix has not been released yet (it will be included in the upcoming Xamarin.iOS 8.10 release).
Comment 11 Rolf Bjarne Kvinge [MSFT] 2015-07-17 05:01:50 UTC
*** Bug 32048 has been marked as a duplicate of this bug. ***