Javascript 当用户退出其中一个选项卡时,用户如何自动退出所有打开的选项卡

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42111784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:54:55  来源:igfitidea点击:

How user will Logout from all open tabs automatically when user logs out in one of them

javascriptphpjqueryajax

提问by Rushil Pachchigar

I have created a Login page, amongst many others pages, which contains code to check the session. If the user doesn't have a session then all pages will reload and redirect to the logout page. This script is called every three seconds.

我创建了一个登录页面,其中包含许多其他页面,其中包含检查会话的代码。如果用户没有会话,则所有页面都将重新加载并重定向到注销页面。该脚本每三秒调用一次。

The code I've written is working fine but I want implement it another way. When the user logs out, all open tabs reload/refresh causing the user to be logged out. Is that possible?

我编写的代码运行良好,但我想以另一种方式实现它。当用户注销时,所有打开的选项卡都会重新加载/刷新,导致用户注销。那可能吗?

sessioncheck.php:

sessioncheck.php:

<?php
session_start();
if(isset($_SESSION['username']) && $_SESSION['username'] != ''){
    echo "true";
}
else {
    echo "false";
}
?>

This code is in every page footer:

此代码位于每个页脚中:

<script>
    function gettatus(){
        $.get("sessioncheck.php", function(data){
            if(!data) {
                window.location = "logout.php";
            }
            setTimeout(function(){
                checkLoginStatus();
            }, 3000);
        });
    }
    $(document).ready(function(){
        gettatus();
    });
</script>

回答by shukshin.ivan

When ajax is useful

当 ajax 有用时

Making an ajax request to your server every 3 seconds is useful just in case 1. you have opened tabs in different browsers 2. or in many computers. 3. or you use very old browsers

每 3 秒向您的服务器发出一次 ajax 请求对于以下情况很有用 1. 您在不同的浏览器 2. 或多台计算机中打开了选项卡。3. 或者你使用非常旧的浏览器

Setting cookie doesn't work.

设置 cookie 不起作用。

Approach using setting cookie doesn't work since one tab is not aware of changed cookies in another tab. That's because of document(where cookies are got from with getCookie) of tab A is not changing without request to a server. You can open two tabs of SO and try to set setCookie('name', 'val', 1)in one tab and look at document.cookiein the other tab.

使用设置 cookie 的方法不起作用,因为一个选项卡不知道另一个选项卡中更改的 cookie。这是因为document选项卡 A 的(使用 getCookie 获取 cookie 的地方)在没有请求服务器的情况下不会改变。您可以打开 SO 的两个选项卡并尝试setCookie('name', 'val', 1)在一个选项卡中设置并document.cookie在另一个选项卡中查看。

How to make another tabs knew about logout immediately

如何让另一个选项卡立即知道注销

If you need to logout all tabs of the same browser, it would be great to pass signals between tabs. There are a couple of methods, I want to tell you about using localStorage(demo here).

如果您需要注销同一浏览器的所有选项卡,最好在选项卡之间传递信号。有几种方法,我想告诉你使用localStoragedemo here)。

You can attach a listener to a storageevent (fired when storage item is changed) and send a logout-eventsignal.

您可以将侦听器附加到storage事件(在更改存储项时触发)并发送logout-event信号。

localStorage.setItem('logout-event', 'logout' + Math.random());

Every other tab will get it with a listener.

每个其他选项卡都会通过侦听器获取它。

window.addEventListener('storage', function(event){
    if (event.key == 'logout-event') { 
        // ..
    }
});

What if old browsers without localStorage

如果旧浏览器没有 localStorage

You can use both approaches - localStorageand auto-refresh, for example every 60 seconds, just to be sure it works when tabs are opened at different computers. If localStoragedoesn't work (very old browsers), auto-refresh every 3 seconds.

您可以使用这两种方法 -localStorage和自动刷新,例如每 60 秒一次,以确保在不同计算机上打开选项卡时它可以正常工作。如果localStorage不起作用(非常旧的浏览器),每 3 秒自动刷新一次。

The following fiddle showshow to deal with it.

下面的小提琴表演如何对付它。

What else?

还有什么?

You can use node.js+ socket.ioto send signals between all browsers of a user. It works rapidly and will logout a user on every device, but it is a little harder to deal with than a common jQuery.

您可以使用node.js+ socket.io在用户的所有浏览器之间发送信号。它运行迅速,并会在每个设备上注销用户,但它比普通的 jQuery 更难处理。

回答by king neo

lets consider somethings that you are using php session and you are checking following code every time you are loading your pages or after some time duration

让我们考虑一下您正在使用 php 会话的内容,并且您每次加载页面或一段时间后都会检查以下代码

<?php
    session_start();
    if(isset($_SESSION['username']) && $_SESSION['username'] != '')
        echo true;
    else 
        echo false;
?>

So on your logout.php file you are probably doing something like this unset($_SESSION['username']); and session_destroy();

所以在你的 logout.php 文件中,你可能正在做这样的事情 unset($_SESSION['username']); 和 session_destroy();

Therefore when your page will call that checking php you will find false in return and that following user will no longer get access from any browser and any pages. And For automatically logout try this

因此,当您的页面调用该检查 php 时,您将发现 false 作为回报,并且该用户将不再从任何浏览器和任何页面获得访问权限。而对于自动注销试试这个

$sessionTTL = time() - $_SESSION["timeout"];
if ($sessionTTL > $inactive) {
    session_destroy();
    unset($_SESSION['username']);
    echo false;

Note: you must set $inactive = 6000;(for example) as global variable while login

注意:您必须$inactive = 6000;在登录时将(例如)设置 为全局变量

回答by Apul

Ajax requests frequently to server to check whether the user is still logged in or not. But this will make a huge server loadand also consume network bandwidth of user

Ajax 经常向服务器请求检查用户是否仍然登录。但这会造成巨大的服务器负载并消耗用户的网络带宽

the load to the server disables this option. I've tested it.

服务器的负载禁用此选项。我已经测试过了。

回答by Sagar V

For this, you have two choices. Either store the session values in server and make Ajax requests frequently to server to check whether the user is still logged in or not. But this will make a huge server load and also consume network bandwidth of user. Or else,

为此,您有两个选择。要么将会话值存储在服务器中,并经常向服务器发出 Ajax 请求以检查用户是否仍然登录。但这会造成巨大的服务器负载,也会消耗用户的网络带宽。要不然,

check the logged in cookie still exists or not in browser frequently. This will be the good approach.

经常检查浏览器中登录的cookie是否仍然存在。这将是一个很好的方法

Both can be performed by setTimeoutor setInterval

两者都可以由setTimeoutsetInterval

But the second one should be good.

不过第二个应该不错。

回答by Sagar V

Here is what you need. In this, snippet shows some error I dont know why. So, please copy the javascript code to browser console(f12) and check it. It worksWhen user login, you must use

这是你需要的。在此, 代码段显示了一些我不知道为什么的错误。因此,请将 javascript 代码复制到浏览器控制台 (f12) 并检查它。它有效当用户登录时,您必须使用

setCookie('loggedin','true',1);

Here we are setting a cookie called logged in

这里我们设置了一个名为 login 的 cookie

 
function setCookie(cookiename, cookievalue, expdays) {
  var d = new Date();
  d.setTime(d.getTime()+(expdays * 24 * 60 * 60 * 1000));
  var expires = "expires=" + d.toUTCString();
  document.cookie = cookiename + "=" + cookievalue + "; " + expires;
}
function getCookie(cookiename) {
  var name = cookiename + "=";
  var startPos = document.cookie.indexOf(name);
  if(startPos == -1) return null;
  startPos+=(name.length);
  if(document.cookie.indexOf(";",startPos) == -1){
    return document.cookie.substring(startPos,document.cookie.length);
  }
  else{
    return document.cookie.substring(startPos,document.cookie.indexOf(';',startPos));
  }
return null;
}


function checkCookie() {
   var loggedin = getCookie("loggedin");
   if (loggedin && loggedin !=null) {
     // Logged in
     //do  nothing
   }
   else{
     window.location.href="login.php";
   }
}
<!-- use the below code in logged in home page to check whether the user is logged in still or not in a time interval of 1 second. Change 1000 as per your need.//-->
<body onload = "setTimeout(checkCookie,1000);">