'Better way to get browser culture in Blazor webassembly / client app
I know how to get the current culture information for Blazor server app by using HTTPContext with IRequestCultureFeature. Is there any better way to get current browser culture in Blazor webassembly (wasm) / client app?
Solution 1:[1]
Currently client size Blazor does not have a way to get culture data because mono on webassembly does not implement it (yet - tracked on github).
As far as I know, your best option is going to be able to find it with javascript, and then send it to Blazor with JsInterop
.
Something like this to get you started, in the index page in a script tag:
window.getCulture = function () {
return (navigator.languages && navigator.languages.length) ? navigator.languages[0] :
navigator.userLanguage || navigator.language || navigator.browserLanguage || 'en';
}
Then in Blazor:
@page "/"
@inject IJSRuntime JSRuntime
@code{
protected override async Task OnInitializedAsync()
{
var browserLocale = await JSRuntime.InvokeAsync<string>("getCulture");
Console.WriteLine(browserLocale);
}
}
Then check the console window and you'll see the culture printed.
Edit: Actually someone made an open source package for this that may be easier to use:
https://github.com/Blazored/Localisation
https://www.nuget.org/packages/Blazored.Localisation/
Edit 2: Blazored.Localisation is deprecated, you can use Blazored.LocalStorage instead:
https://github.com/Blazored/LocalStorage
https://www.nuget.org/packages/Blazored.LocalStorage/
Solution 2:[2]
You can request the browser language using JSInterop:
window.browserJsFunctions = {
getLanguage: () => {
return navigator.language || navigator.userLanguage;
},
getBrowserTimeZoneOffset: () => {
return new Date().getTimezoneOffset();
},
getBrowserTimeZoneIdentifier: () => {
return Intl.DateTimeFormat().resolvedOptions().timeZone;
},
};
@inject IJSRuntime _jsRuntime
@code {
string _cultureName;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
_cultureName = await _jsRuntime.InvokeAsync<string>("browserJsFunctions.getLanguage");
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | LaCrotte |
Solution 2 | agua from mars |