Advanced Functionality in Blazor WebAssembly
Learn about browser compatibility, interop, and enabling location change events.
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:
<ItemGroup><SupportedPlatform Include="browser" /></ItemGroup>
Microsoft decorates unsupported APIs, as shown in the following code:
[UnsupportedOSPlatform("browser")]public void DoSomethingOutsideTheBrowserSandbox(){...}
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 can persist up to 5 MB of data per visitor indefinitely:
...