Blazor, Mono, and WebAssembly
WebAssembly (Wasm) is a binary instruction format that is designed to provide a compilation target for high-level languages like C#. Recently Microsoft began experimenting with WebAssembly to bring .NET to the browser using the Mono run-time. Mono provides the basic plumbing allowing .NET libraries (.dll’s) to run on WebAssembly.
Mind the gap
For the function to be visible to Blazor, we’ll need to add it to the scope of window. As a best practice, additional namespaces can be added using a module pattern, this protects our methods from conflicting with other code on the scope of window. Within our namespace, we define a function to call the native window prompt() method.
Since Blazor’s UI process is capable of running on a separate thread from the application InvokeAsync should be used by default.
The ShowPrompt method is now available to use within the application. We can call PromptAsync from a Blazor component by calling the method and awaiting a result.
In the following example, we’ll trigger a browser prompt when the user clicks on the component. When the prompt is closed the result is returned to the component’s Message field which is data-bound and rendered to the component. To ensure the new value is updated when data-binding occurs, we’ll call StateHasChanged to instruct Blazor to re-render the component.
LogRocket: Full visibility into your web apps
LogRocket is a frontend application monitoring solution that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.