Advanced Functionality in Blazor WebAssembly
Explore advanced functionality in Blazor WebAssembly including browser compatibility analyzers to detect unsupported APIs, integrating JavaScript through interop to access browser features, managing navigation with location change event handling to protect unsaved data, and utilizing various Blazor component libraries. This lesson enables you to build more interactive and reliable web applications using these techniques.
Understanding the browser compatibility analyzer for Blazor WebAssembly
With .NET 6 and later, Microsoft has unified the .NET library for all workloads. However, although, in theory, this means that a Blazor WebAssembly app has full access to all .NET APIs, in practice, it runs inside a browser sandbox, so there are limitations. If we call an unsupported API, this will throw a PlatformNotSupportedException.
To be forewarned about unsupported APIs, we can add a platform compatibility analyzer that will warn us when our code uses APIs unsupported by browsers. Blazor WebAssembly App and Razor Class Library project templates automatically enable browser compatibility checks.
To manually activate browser compatibility checks, for example, in a Class Library or classlib project, add an entry to the project file, as shown in the following markup:
Microsoft decorates unsupported APIs, as shown in the following code:
Note: If we create libraries that should not be used in Blazor WebAssembly apps, then we should decorate our APIs in the same way.
Interop with JavaScript
By default, Blazor components do not have access to browser capabilities like local storage, geolocation, and media capture, or any JavaScript libraries like React or Vue. If we need to interact with them, we can use JavaScript Interop.
Example
Let’s see an example that uses the browser window’s alert box and local storage that ...