0

I have a Blazor web Assembly that runs on windows and the Web I want to log out the user when the Windows/Tab closes.

Is it possible to do it without JavaScript? if yes how can we do it by using C#? if not then how can we do it by using JavaScript?

Ali
  • 300
  • 4
  • 11

1 Answers1

0

I don't think it will possible without Javascript as you will likely need to tie into the window.onbeforeunload. Your application could include a script that creates a handler for this event and execute some logic to perform your logout routine. There are some caveats here. Your logout routine cannot be async as the browser will likely kill the thread before the async routine completes.

Depending on how you implemented your client side authorization you should just be able to clear a cookie or some other persisted data in the browser that lets the application know the user is logged in. If you need to send a request back to the server you could send an synchronous ajax request using Javascript but this may not be supported by some browser. I do believe that chrome supports it.

This post window.onbeforeunload ajax request in Chrome provides some details about how to implement this in Javascript.

groogiam
  • 169
  • 4
  • I've not used JavaScript yet. I don't know how to use it in the Blazor, do u how to do it? – Ali Aug 28 '22 at 12:47
  • Here is the documentation for JsInterop. https://learn.microsoft.com/en-us/aspnet/core/blazor/javascript-interoperability/?view=aspnetcore-6.0 You would essentially just need to include a javascript file in your main page wwwroot/index.html for wasm or Pages/_Layout.cshtml for server. This file would then wire up the onbeforeunload mentioned above. The actual implementation is dependent on how your app stores it's credentials. – groogiam Aug 29 '22 at 17:55
  • See https://learn.microsoft.com/en-us/aspnet/core/blazor/javascript-interoperability/?view=aspnetcore-6.0#location-of-javascript for more details of where to add your js files. – groogiam Aug 29 '22 at 18:02