I found this post on how to write a cookie with Blazor (as it turns out, that involves JavaScript). Using the sample from the post, I made my own version, with both a Write and a Read function. So it looks like this:
<script>
window.blazorExtensions = {
WriteCookie: 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=/";
};
ReadCookie: function (cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
}
</script>
Only problem is... It doesn't work :-(
If I only have theWriteCookie
method it works. If I only have the ReadCookie
method it works. But if I have both, it does not work.
From the looks of it, the window
part is a module, but I could be wrong. However, this it what VS Code says, in the tool tip:
Can anyone explain to me, why this does not work? I tried Google, but since I struggle with the terminology, it's hard to find something useful. I am used to C# and thought that the window.blazorExtension
was some sort of namespace.
If it's any help, here is how I invoke the functions:
public async Task WriteCookeAsync() {
var test = await JSRuntime.InvokeAsync<object>("blazorExtensions.WriteCookie", "Color", colorCode, 7);
}