JavaScript interaction is about how Blazor interacts with JavaScript. In this tutorial, you will discover:
You can download the example code used in this topic on GitHub.
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.
JavaScript interaction technique allows you to:
The following list is the common mistakes when interacting with the 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.
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:
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:
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.