Blazor Bites Series

Post valid for: Blazor 0.4.0
Please remember that Blazor is an experimental project and is going to be changing regularly. IT IS NOT PRODUCTION READY.

JavaScript Interop

It's great that with Blazor we can now use C# in the browser. But, unfortunately, we can't yet do everything with it. Currently WebAssembly isn't able to directly access the DOM API, which means that Blazor is not able to either. But fear not, JavaScript and WebAssembly can work together; WebAssembly is able to call JavaScript functions.

Part of Blazor is implemented and lives in the JavaScript world. It is though this interface that Blazor is able to manipulate the DOM to render the UI and to hook into various DOM events. It is also how developers can register and call their own JavaScript functions from C# code.

Registering JavaScript functions with C#

In order to use a JavaScript function from C# it has to be registered with one of Blazors JavaScript functions, registerFunction. This is a simple function which takes an identifier, which is the identifier you will use to call this function from C#. And a implementation, which is the JavaScript function to be called.

One thing to note is that currently your JS function must have a return value. If you don't provide one, things blow up.

    Blazor.registerFunction('JavaScriptAlert', (message) => {
        return true;

Calling JavaScript functions from C#

From C#, you can then use either RegisteredFunction.Invoke or RegisteredFunction.InvokeUnmarshalled, with your identifier, to run your JavaScript function. The difference between Invoke and InvokeUnmarshalled is that when calling Invoke all arguments and return values are marshalled (passed) using JSON. When calling InvokeUnmarshalled this is not the case, you would have to handle how you pass objects across the C#/JavaScript boundary manually.

public static void TriggerJsAlert()
    RegisteredFunction.Invoke<bool>("JavaScriptAlert", "I was invoked from C#!");

Calling C# methods from JavaScript

As of 0.4.0 calling .NET methods from JavaScript has been greatly improved. While it was possible in earlier version of Blazor it was a low level API. In order to call into .NET, the method will need to be static, non-generic, have no overloads and concrete JSON serialisable parameter types.

You make the call using the Blazor.invokeDotNetMethod as shown below.

    type: {
        assembly: 'AssemblyName',
        name: 'Namespace.ClassName'
    method: {
        name: 'MethodName'

Wrapping up

That's the end of another Blazor Bites post. I have been getting some really good feedback about the series which is great to hear. If there is anything specific you want me to cover please leave a comment below and I'll see what I can do.