Search code examples
blazorblazor-webassemblyasp.net-blazor

Get the window size on page load


Is it possible to get the window size on the page load?


Solution

  • I found a way of doing something similar that fixes my problem.

    First, set this script function on index.html file:

    window.getWindowDimensions = function () {
        return {
            width: window.innerWidth,
            height: window.innerHeight
        };
    };

    Then on your page where you want to read the screen width you need to read this function:

    [Inject] IJSRuntime JSRuntime { get; set; }
    protected int WindowWidth { get; set; }
    protected override async Task OnInitializedAsync()
    {
        var dimension = await JSRuntime.InvokeAsync<WindowDimension>("getWindowDimensions");
        WindowWidth = dimension.Width;
    }
    

    So every time the page reload we know the width of the window.