JavaScript interaction
JavaScript interaction is about how Blazor interacts with JavaScript. In this tutorial, you will discover:
Why JavaScript interaction technique?
What you can do with JavaScript interaction?
Common mistakes.
You can download the example code used in this topic on GitHub.
Why JavaScript interaction technique?
Blazor uses WebAssembly as its core. Despite WebAssembly has been improved a lot and there is an ongoing plan to upgrade WebAssembly, WebAssembly is not ready yet to take over the role of JavaScript. Furthermore, interacting with JavaScript allows you to use the JavaScript APIs and JavaScript libraries, so that you can take advantages of the existing JavaScript libraries.
What you can do with JavaScript interaction?
JavaScript interaction technique allows you to:
Load JavaScript library.
Use JavaScript APIs.
Call C# methods from JavaScript.
Transfer data between JavaScript and C#.
Isolates JavaScript modules.
Common mistakes
The following list is the common mistakes when interacting with the JavaScript.
Try to call .NET library method directly from JavaScript.
Make an infinitive loop.
Try to remove a Blazor DOM.
Use JS as script.
Try to call .NET library method directly from JavaScript
JavaScript interaction allow you to call C# methods from JavaScript. However, you need to specify which C# methods can call from JavaScript before actually calling it. Therefore, you cannot call a method that is not specified to call in JavaScript. For example, you cannot call methods from System.Math
(or any other libraries) unless you wrap it inside and method and specify that method to be able to call by JavaScript.
Make an infinitive loop
This common mistake usually made by the beginners. When making a call to a JavaScript function A and that JavaScript function A calls the C# method B again then the C# method B making a call to the JavaScript function A, thus create an infinitive loop. The following image illustrates this mistake.
The following video illustrates what will happen when you make this mistake:
Try to remove a Blazor DOM
JavaScript is to modify DOM. However, when both Blazor Server and JavaScript modify a same DOM, a confliction will occur. The result would be the website stopped working and need to be refreshed. The following video illustrates this situation:
Use JavaScript as script
Blazor Server cannot use JavaScript as script, Blazor Server can only call predefined functions. For example, you cannot create a new object with new
keyword directly in Blazor, to do so, you need to declare a function to create a new object then call the function.