DEV Community 👩‍💻👨‍💻

Cover image for Write to the console.log with styles from Blazor
Emanuele Bartolesi
Emanuele Bartolesi

Posted on

Write to the console.log with styles from Blazor

The console is a very good companion for every web developer.
We use the console to log everything and for various reasons.
In this post I will show how to add some CSS styles to the console application just for having fun or for adding value to the logs in the developer tools console of the browser.

To add CSS styles to the console, we use the format specifier %c at the beginning of the string.
And as a second parameter we can add some CSS rules.
Take a look to the script below:

console.log("%cThis is a red text", "red");
Enter fullscreen mode Exit fullscreen mode

Easy.
But how we can use the same features, but from a Blazor application?
It's easy as well.

Open the razor page where you want to add the console formatting and insert the injection for JSRuntime.
Then in the InitializedAsync or on a click event, call the console.log method from Blazor.
You can use the same parameters that you are using from JavaScript.
Below you can find the entire code to add to your application.

@code {
    @inject IJSRuntime JSRuntime

    protected override async Task OnInitializedAsync()
    {
        await JSRuntime.InvokeVoidAsync("console.log", "%cRed Origin  5.0.1 🚀", "color:#0dd8d8; background:#0b1021; font-size:1.5rem; padding:0.15rem 0.25rem; margin: 1rem auto; font-family: Rockwell; border: 2px solid #0dd8d8; border-radius: 4px;font-weight: bold; text-shadow: 1px 1px 1px #00af87bf;");
    }
}
Enter fullscreen mode Exit fullscreen mode

In this case, in the console you can find a message like in this picture:


Thanks for reading this post, I hope you found it interesting!

Feel free to follow me to get notified when new articles are out 🙂

Top comments (0)

👋 New to DEV?

Head over to our Welcome Thread and tell us a bit about yourself!