Skip to content

Instantly share code, notes, and snippets.

@Eonasdan
Last active July 14, 2022 01:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Eonasdan/9cbd63c7e2ebd8624191a97befb64f00 to your computer and use it in GitHub Desktop.
Save Eonasdan/9cbd63c7e2ebd8624191a97befb64f00 to your computer and use it in GitHub Desktop.
Console log extensions for Blazor

JS Extensions

Allows more complex logging in Blazor. Console.WriteLine doesn't support objects or lists but these methods do.

Use as

[Inject]
private IJSRuntime Js { get; set; } = default!;

await Js.LogAsync(myObject);
public static class JsRuntimeExtensions
{
/// <summary>
/// Calls "console.log" on the client passing the args along with it.
/// </summary>
/// <example>
/// LogAsync("data") //same as console.log('data')
/// </example>
/// <example>
/// LogAsync("data", myData) //same as console.log('data', myData)
/// </example>
/// <param name="js"></param>
/// <param name="args"></param>
public static async Task LogAsync(this IJSRuntime js, params object?[]? args)
{
await js.InvokeVoidAsync("console.log", args);
}
/// <summary>
/// Calls "console.table" on the client passing the args along with it.
/// </summary>
/// <example>
/// TableAsync(myData) //same as console.table(data)
/// </example>
/// <example>
/// TableAsync(myData, new []{"firstName", "lastName"}) //same as console.table(myData, ["firstName", "lastName"])
/// </example>
/// <param name="js"></param>
/// <param name="o"></param>
/// <param name="fields"></param>
public static async Task TableAsync(this IJSRuntime js, object? o, string[]? fields = null)
{
await js.InvokeVoidAsync("console.table", o, fields);
}
/// <summary>
/// Set the provided object to a global variable.
/// </summary>
/// <example>
/// SetGlobalAsync("foo", myData) //same as window.foo = myData
/// </example>
/// <param name="js"></param>
/// <param name="name"></param>
/// <param name="o"></param>
public static async Task SetGlobalAsync(this IJSRuntime js, string name, object? o)
{
var json = JsonConvert.SerializeObject(o);
await js.InvokeVoidAsync("setGlobal", name, json);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment