ThePaye
ThePaye

Reputation: 1611

mvc3 detect website (application) is closing

I'm building a website with mvc3 and I need to delete a data in my database only when the application is closing. (The user click on the red x).

I tried with javascript using the onbeforeunload event, but this event happens everytime I go into a new page in my application.

Is it possible to detect when the user closes the window?

Upvotes: 2

Views: 4803

Answers (3)

Lester
Lester

Reputation: 4413

It's not possible. But, what you can do is have a small javascript block that will make an ajax call every n minutes/seconds to tell the server that the user still has the browser open.

This way, you can set a timeout that says if after 5 minutes we haven't heard from the user we can delete the data in the database (or whatever action you need to do).

To implement the timeout logic there are 2 options:

  1. You have a separate service (console app or windows service) running on some interval that checks if any user's timeout is greater than some value. If it is then perform whatever action you need.

  2. If any user performs an action that would have been blocked, you first check if any user still has it active (the timeout value is greater than current time). If there is, you block the user, if there isn't, you can remove that old timeout value since it's expired.

Upvotes: 6

soniiic
soniiic

Reputation: 2685

Use a synchronous ajax request in the window.unload event.

When the user goes to a different page, or closes, or refreshes then this event will fire. You could call a service on your web app to notify it that the user is no longer editing the document

After a very quick google, I saw this snippet here

$(window).unload(function() {
    $.ajax({
        url: 'resetTheDocument?id=whatever',
        async: false,
        cache: false,
        type: "POST",
        data: "My work here is done"
    });
});

Upvotes: 3

mreyeros
mreyeros

Reputation: 4379

Good morning you could try adding your logic to the global.asax file in the Session_End method to delete the record in your database.

Upvotes: 1

Related Questions