How to execute code when the user navigates away (unbeforeunload)?

I am setting a user presence status if a user views a certain page. If the user navigates away, I want to reset the presence status. This works, if the user navigates inside the Meteor app (using .onDestroy()), but onDestroy() is not called if the user navigates to a different website or closes the browser window.

Setting an onbeforeunload handler on the window object did not work either. Is there a way to safely detect if a user wants to navigate away in Meteor?

Why did window.onbeforeunload handler did not work for you? It’s a safe way to detect if the window is about to be closed and should work in Meteor too.

I’ve successfully been using

Meteor.startup(function(){
    $(window).bind('beforeunload', function() {
        closingWindow();
    });
});

closingWindow = function(){
    Meteor.logout();
}

for forcing logouts in order to avoid some google multiple-account problems.

2 Likes

Ok, thanks. I will try bind() as well.

My first attempt was with $(window).unload(), but this did not work. I read somewhere on StackOverflow that this was because Meteor overwrites any unload() handler on startup.

This did not work either. The handler is not firing, neither if the user navigates to another page, nor when he closes the tab. I tried it both in the Meteor.startup() code as you suggested and in a template onCreated() handler. Neither did the trick.

I have to correct myself. It is working, I just could not see any logs, and the browser did not accept an alert() in the hanlder. But a Method.call() is routed to the server, this is what I needed. Thanks.

Hm, I’ve rechecked and it is a Meteor 1.0.4.2 app that has not been upgraded. Maybe something has changed in between.

I’ve tried this and it worked for me whenever I am closing a window /tab but when I reload/refresh the browser the user will logout by the server:

Error logging in with token: Error: You've been logged out by the server. Please log in again. [403]

These code you wrote is good work.
Can you give me some tip for this?
I just want to pop up confirm window, so user can decided if they escape or not when they try to escape current page or click history back button.
It’s hard to me.
I’m freshman in meteor.

1 Like