How can I write into the browser´s console via Blazor WebAssembly?

Viewed 31007

In JavaScript we can use the following call to write debug output to the browser´s console:

console.log("My debug output.");

Output in Google Chrome:

console output in google chrome

How can I log "My debug output" in my component to the browser´s console via Blazor WebAssembly?

<button @onclick="ClickEvent">OK</button>

@code {

    private void ClickEvent()
    {
        // console.log("My debug output.");
    }
}
5 Answers

I usually do something like this:

Console.WriteLine("My debug output.");

if it's Blazor WebAssembly, I see the message in the browser´s console.

If it's Blazor Server App I see the message in the Output window. (In the output window, there is a dropdown - select: " ASP.NET Core Web Server")

Hope this helps...

If your using Blazor Server (not WebAssembly) you can only write to the browser console using JSInterop. I wrote a wrapper class like this:

public class JsConsole
{
   private readonly IJSRuntime JsRuntime;
   public JsConsole(IJSRuntime jSRuntime)
   {
       this.JsRuntime = jSRuntime;
   }

   public async Task LogAsync(string message)
   {
       await this.JsRuntime.InvokeVoidAsync("console.log", message);
   }
}

Then in your page, you can inject the JsConsole and use it:

await this.JsConsole.LogAsync(message); //Will show in the browser console.

You can user an ILogger<T> that give you the possibility to write warning or error in the console :

@using Microsoft.Extensions.Logging
@inject ILogger<MyComponent> _logger
...
@code {

     protected override void OnInitialized()
     {
          _logger.LogWarning("warning");
          _logger.LogError("error");
     }
}

Building on @Greg Gum's answer, javascript's console.log() can also accept any object. Therefore if you send it an object, you will get a nice output of the full object as a javascript object, rather than just a string.

public class JsConsole
{
   private readonly IJSRuntime JsRuntime;
   public JsConsole(IJSRuntime jSRuntime)
   {
       this.JsRuntime = jSRuntime;
   }

   //change this parameter to object
   public async Task LogAsync(object message)
   {
       await this.JsRuntime.InvokeVoidAsync("console.log", message);
   }
}
Related