Live Chat Icon For mobile
Live Chat Icon

How do you create a cookie in the client-side of Blazor?

You have to use JS Interop to create a cookie in Blazor.

[Razor Page]

@page "/" 

@inject IJSRuntime JSRuntime 
<p>Here created cookies</p> 
<button onclick="@(() => CreateCookie("myCookie", "myValue", 7))">Create Cookie</button> 

@code { 

    private async void CreateCookie ( string name, string value, int days ) 
    { 
        var test = await JSRuntime.InvokeAsync<string>("methods.CreateCookie", name, value, days); 
    } 
} 

[index.html]

<body> 
    …. 
    <script > 
        window.methods = { 
            CreateCookie: function (name, value, days) { 
                var expires; 
                if (days) { 
                    var date = new Date(); 
                    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); 
                    expires = "; expires=" + date.toGMTString(); 
                } 
                else { 
                    expires = ""; 
                } 
                document.cookie = name + "=" + value + expires + "; path=/"; 
            } 
        } 
    </script> 
</body> 

View Sample in GitHub

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.