简体   繁体   中英

Clear PHP session on tab close?

I'm trying to logout each time the user closes it's tab. I've saw all similar questions, but I still haven't found anything that works.

Here's what I've done:

<script type="text/javascript">
    $(document).ready(function() {
        $(window).bind("beforeunload", function() {
            confirm("Do you really want to logout?") && $.ajax({
                type: "GET",
                url: "/admin/account/logout"
            })
        })
    });
</script>

I've tried without the confirm , but it still doesn't work. I'm absolutely sure that it can be done, since my bank's website has the same functionality.

EDIT: Without the confirm it does fire the logout ajax, but even when I browse trough the pages. Which reminds me, that my bank's website uses something like AngularJS, which is not exactly a true link-browsing system, right? Maybe that's why it works there?

The beforeunload is fired every time you say your browser to unload current html. It's happens even if you click on a link. When you cosle a tab, you also close the enviroment where that page's js was executed. I don't think it can be done natively.

The issue with your code is that the request is executed asyncronously and gets terminated with the closing of the window. If you set the async paramenter to false the ajax request will get executed before the tab/window is closed.

Unfortunately this won't solve your problem since this event is fired every time you're about to leave the page. If you are just trying to hack a solution you can use the approach mentioned here: https://stackoverflow.com/a/44057659/5173095 - trigger a timeout on the server side and logout the user if he doesn't make another request after the timeout has passed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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