JavaScript Interop
Why Do We Need
JavaScript?
Blazor requires
JavaScript to function. Certain events are only activated in JavaScript, and to
utilize these events, we must implement an interop. A couple of libraries that
depend on JavaScript to function are named Blazm.Components and Blazm.Bluetooth.
The first component is a
grid that leverages JavaScript interop to initiate C# code (JavaScript to .NET)
when the window is resized, eliminating columns if all cannot fit within the
window. When this occurs, the C# code invokes JavaScript to obtain the dimensions
of the columns based on the client width, a detail known only to the web
browser, and removes columns as necessary based on that information. The second
component, Blazm.Bluetooth, allows for interaction with Bluetooth
devices using Web Bluetooth, a web standard accessible via JavaScript. It uses
two-way communication. Bluetooth events can trigger C# code that can iterate
over devices and send data to them. They are both open-source.
.NET To JavaScript
Calling JavaScript from
.NET is pretty simple. There are two ways of doing that-
• Global JavaScript
• JavaScript Isolation
Global JavaScript (the
old way)
One technique is to use
the JavaScript window to make the JavaScript method we wish to call globally
accessible. This is something of a bad practice because it is accessible by all
scripts and might replace the functionality in other scripts (if we were to
unintentionally use the identical names).
There are two different
methods we can use to call JavaScript:
- InvokeVoidAsync,
which calls JavaScript, but doesn’t expect a return value.
- InvokeAsync<T>,
which calls JavaScript and expects a return value of type T.
JavaScript Isolation
In .NET 5, we introduced
a new method for incorporating JavaScript called JavaScript Isolation, which
offers a more streamlined approach to executing JavaScript. This approach
avoids the use of global functions and eliminates the need to link to the JavaScript
file directly. This is beneficial for both component developers and end users
since JavaScript will be loaded on demand. It will only load the script once,
and there is no need to reference the JavaScript file, making it simpler to
start using a library.
Conclusion
We have successfully
learnt the method of calling JavaScript from .NET.
Comments
Post a Comment