简体   繁体   中英

Detecting browser's closing tab

I am currently using window.onbeforeunload function on my javascript to detect browser's closing tab. I only want the function to run when the users click on closing tab. However, this function also run when the user navigates from one page to another page (action result to action result). I am writing code on asp.net mvc 4. Thank in advance.

window.onbeforeunload = function () {

};

There is a way in ASP.net MVC to do that but you have to consider all the scenarios.

As you said onbeforeunload runs for navigating. So if you could find a way to consider that the user is not navigating but he is not there anymore you can achieve your goal.

So what I suggest is to use SignalR + onbeforeunload for that because in any ways whether you navigate or close the tab in SignalR the user will be disconnected and you have an OnDisconnected event for that.

So now you know that the user has left the page but you don't know if he has navigated or closed the tab. In this case you use onbeforeunload to send message to server if the onbeforeunload event was triggered. Now consider the two solution together and you're gold.

So what happens: In Closing the Tab or Window: onbeforeunload is called and you send a message to server to say that connectionId = X has navigated and if after a short amount of time the connectionId in the server is passed to OnDisconnected you are sure that he has closed the tab.

Of course these two operations happen in different threads and they are a little over the top but if you are serious in having this recognition in your website this would be my approach as I am not 100% confident on the solution to be a great solution but it might be one of the few ones!

Of course also if you don't want to work with SignalR , Websocket is also another way of doing it instead of SignalR but is not going to work in older browsers which SignalR can.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM