简体   繁体   English

角度:关闭窗口时用户注销

[英]Angular: user logoff on closing window

I have an angular application where, when a user logs in, I set his status to "online" on the db. 我有一个角度应用程序,当用户登录时,我在数据库上将他的状态设置为“在线”。 If this user close the browser, instead of performing the menu action logout, how can I update his status to "offline"? 如果该用户关闭浏览器,而不是执行菜单操作注销,我如何将其状态更新为“离线”? I tried to use the "$window.onbeforeunload" event and call a web service to logout the user. 我试图使用“ $ window.onbeforeunload”事件并调用Web服务注销用户。 The code runs but it seems that the execution would be "cut off" by the browser: the service is never called "really". 该代码可以运行,但是浏览器似乎会“中断”执行:该服务永远不会被称为“真正”。

One thing to note is that the onbeforeunload event is not supported by all browsers, it's a non-standard event. 需要注意的一件事是,并非所有浏览器都支持onbeforeunload事件,这是一个非标准事件。

Also, your use-case has the caveat of firing that event whenever a user submits a form, navigates out of the page, etc. 此外,您的用例需要警告,无论何时用户提交表单,导航到页面外等,都会触发该事件。

You'd need to filter out those "events" from the onbeforeunload to make sure that your logic would only execute with an actual window close. 您需要从onbeforeunload过滤掉那些“事件”,以确保您的逻辑仅在关闭窗口时执行。

You can do that using jQuery: 您可以使用jQuery来做到这一点:

    var ignore;
    $('a').live('click', function() { ignore = true; });

    etc...

    $(window).bind("beforeunload", function() { 
        return ignore || confirm("Do you want to close the browser/tab?"); 
    });

The problem is that even with this, after clicking OK any subsequent code would never be executed because...well, the window is effectively closed :) 问题是,即使这样,单击“确定”后,也不会再执行任何后续代码,因为...好吧,窗口实际上已关闭:)

The only way you could do this was if, for some awkward reason, you could «prevent» the window from Closing while your logic was executed, and Closing it afterwards. 这样做的唯一方法是,由于某种尴尬的原因,您可以在执行逻辑时“防止”关闭窗口,然后再关闭它。

FORTUNATELY this is not possible. 幸运的是,这是不可能的。

So this leaves you with the only way of doing this properly wich is on the server-side, checking for session expiration or something like that. 因此,这使您只能在服务器端正确地进行此操作,以检查会话到期或类似情况。

Use a WebSocket connection or polling, and listen for that to close/stop on the server. 使用WebSocket连接或轮询,然后侦听以在服务器上关闭/停止。

As @António says, you cannot rely on the client to consistently notify you that it's closing. 正如@António所说,您不能依靠客户端来始终如一地通知您它即将关闭。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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