{"id":45,"date":"2019-10-02T22:09:18","date_gmt":"2019-10-02T12:09:18","guid":{"rendered":"http:\/\/blazortips.azurewebsites.net\/?p=45"},"modified":"2020-12-20T19:02:20","modified_gmt":"2020-12-20T09:02:20","slug":"blazor-how-to-ready-window-dimensions","status":"publish","type":"post","link":"https:\/\/blazortips.azurewebsites.net\/blazor-how-to-ready-window-dimensions\/","title":{"rendered":"How to read Window Dimensions in Blazor?"},"content":{"rendered":"\n
Blazor.tips How to read the browser window dimensions <\/p>\n\n\n\n
window.innerHeight and window.innerWidth<\/p>\n\n\n\n
first create a service class to read the dimensions from javascript<\/p>\n\n\n\n
using Microsoft.JSInterop;\n using System.Threading.Tasks;\n\n public class BrowserService\n {\n private readonly IJSRuntime _js;\n\n public BrowserService(IJSRuntime js)\n {\n _js = js;\n }\n\n public async Task<BrowserDimension> GetDimensions()\n {\n return await _js.InvokeAsync<BrowserDimension>(\"getDimensions\");\n }\n\n }\n\n public class BrowserDimension\n {\n public int Width { get; set; }\n public int Height { get; set; }\n }<\/code><\/pre>\n\n\n\nregister the service with the DI on startup.cs<\/p>\n\n\n\n
public void ConfigureServices(IServiceCollection services)\n{\n services.AddRazorPages();\n services.AddServerSideBlazor();\n services.AddScoped<BrowserService>(); \/\/ scoped service\n}<\/code><\/pre>\n\n\n\nadd the javascript codes to read the window dimensions you can add them to the _Host.cshtml file directly or add them to a js file <\/p>\n\n\n\n
<script type=\"text\/javascript\">\n window.getDimensions = function() {\n return {\n width: window.innerWidth,\n height: window.innerHeight\n };\n };\n <\/script><\/code><\/pre>\n\n\n\nadd new razor file to display the dimensions<\/p>\n\n\n\n
@page \"\/dimensions\"\n\n@using BlazorApp.Service\n@inject BrowserService Service\n\n<h1>Window Dimensions<\/h1>\n\n<p>Window Height: @Height<\/p>\n<p>Window Width: @Width<\/p>\n\n<button @onclick=\"GetDimensions\">Get Dimensions<\/button>\n\n@code {\n\n public int Height { get; set; }\n public int Width { get; set; }\n\n async Task GetDimensions() {\n var dimension = await Service.GetDimensions();\n Height = dimension.Height;\n Width = dimension.Width;\n }\n\n}<\/code><\/pre>\n\n\n\n