in the last days I'am trying to read out the browser resolution in my blazor app. I'am trying to do it this way: [JSInvokable] Blazor Methode is invoked by a JS script.
1. My question is: The width and height is only shown in my blazorpage after I reload (manually refresh) the page. I can't call this.StateHasChanged() because my methode is static.
How do I call StateHasChanged or what do I need to do to show the new data? I'am pretty new to ASP.net etc. so please if possible include a code example ;)
Here my Code blazor (serverside) code:
@page "/"
@inject IJSRuntime jsRuntime
<h1>Window Dimensions</h1>
<p>Window Width: @Width</p>
<p>Window Height: @Height</p>
<p>@DebugString</p>
@code {
public static int Width;
public static int Height;
public static string DebugString;
[JSInvokable]
public static async Task GetBrowserDimensions(int width, int height)
{
Width = width;
Height = height;
if (Width < 600)
{
DebugString = "small_UI";
}
if (Width >= 600)
{
DebugString = "big_UI";
}
}
}
and here my .js code:
//------JS Code for the resize stuff incl. timer so that resize doesnt fire every pixel move
var resizeId;
window.addEventListener('resize', function () {
clearTimeout(resizeId);
resizeId = setTimeout(doneResizing, 500);
});
function doneResizing() {
var width= window.innerWidth;
var height= window.innerHeight;
alert('Width: ' +width + ' Height: ' +height);
DotNet.invokeMethodAsync('Blazor_PageResolutionJS', 'GetBrowserDimensions', width, height);
}
//^^^^^^JS Code for the resize stuff incl. timer so that resize doesnt fire every pixel move
2. Is this a okay technic to get the resolution of the browser in order to make UserInterface design choices?
Thank you for reading
You can bypass the need for this by installing the NuGet package https://www.nuget.org/packages/BlazorPro.BlazorSize/
If you're still interested in writing the code yourself, you can find the source for BlazorSize at https://github.com/EdCharbeneau/BlazorSize/tree/master/BlazorSize
The solution to calling StateHasChanged from JavaScript involves using a [JsInvokable] method in .NET. However, if you look through the source of BlazorSize you'll notice there is a lot of extra work needed for properly removing event listeners from the DOM once you're through with them.