Interoperating with Javascript
The Uno boostrapper provides the ability to interoperate from and to Javascript from .NET.
Two techniques are available:
- The use of .NET 7's new generated interop features. It uses code generation to create performant, CSP-Compliant, thread-safe interop and does not make of the unsafe javascript
eval
. - The use of the legacy C#
Interop.Runtime.InvokeJS(...)
and Javascriptmono_bind_static_method(...)
.
Invoking C# code from Javascript
.NET 7 introduces the [JSExportAttribute]
which allows for Javascript to invoke C# static methods in a memory, threading and performance efficient way.
Important
To enable this feature, you'll need to use net7.0
or later in your project's TargetFramework
, and you will need to use the Uno Bootstrapper 7.x or later.
In your C# project (named MyApp
for this example), add the following class:
namespace MyNamespace;
public static partial class Exports
{
[System.Runtime.InteropServices.JavaScript.JSExport()]
public static string MyExportedMethod()
{
return $"Invoked";
}
}
Then in your Javascript, add the following:
async function invokeCSMethod() {
globalThis.myExports = await Module.getAssemblyExports("MyApp");
var result = globalThis.myExports.MyNamespace.Exports.MyExportedMethod();
}
invokeCSMethod();
Invoking Javascript code from C#
Invoking JS functions from C# can be done through [JSImportAttribute]
.
Important
To enable this feature, you'll need to use net7.0
or later in your project's TargetFramework
.
In your C# project (named MyApp
for this example), add the following class:
namespace MyNamespace;
public static partial class Imports
{
[System.Runtime.InteropServices.JavaScript.JSImport("globalThis.myJSMethod")]
public static partial string MyJSMethod();
}
Then in your Javascript, add the following:
function myJSMethod(){
return "myJSMethod invoked!";
}
In the C# code, call Imports.MyJSMethod();
as you would any other method.