如何使用 JavaScript 检查 Session 是否过期
我想在会话过期后将用户从应用程序中的任何位置重定向到“登录页面”。
我如何使用 JavaScript 来实现这一点?
I want to redirect the user to the "Login page" from anywhere in the application once the session is expired.
How can I accomplish that using JavaScript?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
会话的典型实现需要两件事:
这些 cookie 通常设置为会话 cookie。当浏览器关闭时它们就会过期。因此,您无需担心测试它们来实现这一点。
要查明会话在服务器上是否仍然有效,您需要(定期)向服务器发出 HTTP 请求(可以使用 Ajax 执行此操作),并让服务器响应有关会话生命周期的信息。
一个简单的解决方案是返回 true 或 false,如果为 false,则重定向(通过设置
location.href
)。更有效的解决方案是返回会话的剩余生存时间,并使用该信息来确定下次检查的时间(如果为 0,则重定向)。
一个更多
A typical implementation of a session requires two things:
These cookies are usually set up as session cookies. They expire when the browser closes. Thus you don't need to worry about testing them to achieve this.
To find out if the session is still valid on the server, you need to (periodically) make an HTTP request to the server (you can do this with Ajax) and have the server respond with information about the life of the session.
A simple solution would be to return true or false, and then redirect (by setting
location.href
) if it is false.A more efficient solution would be to return the remaining time to live for the session, and use that information to determine when next to check (and redirect if it is 0).
A more
没有必要定期检查会话是否过期,您能做的最好的事情是您可以检查前端事件何时触发,例如提交之前/单击之前等。
服务器时间是我们需要管理的关键资源,以提供更好的应用程序性能。
It is not necessary to do a periodic check of session is expired, the best thing you can do is you can check when event is fired on the front end, Say like before submit / before click etc.
Server time is a key resources we need to manage to give better app performance.