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:

https://platform.uno/docs/articles/wasm-custom-events.html

 

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.

clipboard_image_0.png

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.
iziToast: https://izitoast.marcelodolza.com/

 

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

clipboard_image_4.png

And you will update your JavaScript file to use it:

 

 

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

 

 

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

clipboard_image_3.png

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) => { iziToast.show({ title: 'Info', message: 'Hello from the awesome library.' }); }); }

 

 

It works fine.

clipboard_image_5.png

Conclusion

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:

https://platform.uno/

 

Leave a Reply

Your email address will not be published. Required fields are marked *

*

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