How to use JavaScript libraries on Uno Platform(WebAssembly)

This post has been republished via RSS; it originally appeared at: New blog articles in Microsoft Tech Community.

Uno Platform is one of the development platform tools for cross-platform apps such as UWP, Android, iOS, and WebAssembly.

For WebAssembly, there are JavaScript interop features. I'll explain how to call JS functions from C# on this article.

If you would like to call C# methods from JavaScript, then please check the following document:


Let's call a simple JS function

Preparation to call JavaScript functions is that copy .js file as Embedded resource under WasmScripts folder. If the library also has .css files, then copy those to WasmCSS folder too.


In the case of the library provides simple JavaScript functions like below, you can call the functions using WebAssemblyRuntime.InvokeJS method.



using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; #if __WASM__ using Uno.Foundation; #endif namespace JSInterop { public sealed partial class MainPage : Page { public MainPage() { this.InitializeComponent(); } private void InvokeJSFunctionButton_Click(object sender, RoutedEventArgs e) { #if __WASM__ WebAssemblyRuntime.InvokeJS("sayHello();"); #endif } } }




However, almost all real libraries provide them functions as a module. For example, if you would like to show toast notifications on the web browser, suppose you use iziToast.


You will download it, and copy .js files and .css files as Embedded resource to the WASM project, like below:


And you will update your JavaScript file to use it:



function sayHello() {{ title: 'Info', message: 'Hello from the awesome library.' }); }



However, it doesn't work with the following error:


Because a WASM app of Uno Platform includes require.js, so iziToast detects it when loading, and all functions is provided as a module that name is 'iziToast,' so you have to require it before using it.


The correct code to use iziToast from Uno Platform is as below:



function sayHello() { require(['iziToast'], (iziToast) => {{ title: 'Info', message: 'Hello from the awesome library.' }); }); }



It works fine.



If you would like to call JavaScript functions from Uno Platform, then you should check that the library is a module or just functions or others.


And if you feel Uno Platform is interesting, then please check the official site:


REMEMBER: these articles are REPUBLISHED. Your best bet to get a reply is to follow the link at the top of the post to the ORIGINAL post! BUT you're more than welcome to start discussions here:

This site uses Akismet to reduce spam. Learn how your comment data is processed.