Log out when the browser or tab is closed (Asp Net + Mvc + Framework 5.4.1)

Anto BAro 86 Reputation points
2022-05-09T08:50:48.573+00:00

Hello,

I would like my project to log out when closing the browser (Edge) or when closing the Tab that contains it. The program is in ASP.NET with MVC and Framework 4.5.1.

Now I have inserted this script in _Layout.chtml

<script language="Javascript">   

window.onbeforeunload = function BClose() {return "Do you really want to close?";};

</script

>

and this instruction in the body of the same view

<body onbeforeunload="BClose()" onclick="clicked=true;">

Unfortunately all of this does not work.

The only result produced is that when I move from one view to another, a message box always appears asking me if I want to exit or not.

I have tried numerous examples but none that act when the browser or tab is closed.

Any suggestions or examples?

Regards

Developer technologies | ASP.NET | Other
0 comments No comments
{count} vote

6 answers

Sort by: Most helpful
  1. Aaron 0 Reputation points
    2025-08-05T14:15:15.36+00:00

    Even setting isPersistent=false doesn't apparently do it anymore with modern browsers, unless (supposedly) you turn off the "restore tabs when opening" option. (I havent tried turning that off, because I do depend on it for my workflow.)

    So it seems there is no way to enforce this anymore realistically, except in very controlled environments where you can enforce session restore being off.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.