Read Session Id using Javascript

前端 未结 7 1816
被撕碎了的回忆
被撕碎了的回忆 2020-12-24 06:33

Is it by any means possible to read the browser session id using javascript?

相关标签:
7条回答
  • 2020-12-24 06:50

    Here's a short and sweet JavaScript function to fetch the session ID:

    function session_id() {
        return /SESS\w*ID=([^;]+)/i.test(document.cookie) ? RegExp.$1 : false;
    }
    

    Or if you prefer a variable, here's a simple one-liner:

    var session_id = /SESS\w*ID=([^;]+)/i.test(document.cookie) ? RegExp.$1 : false;
    

    Should match the session ID cookie for PHP, JSP, .NET, and I suppose various other server-side processors as well.

    0 讨论(0)
  • 2020-12-24 07:03

    As far as I know, a browser session doesn't have an id.

    If you mean the server session, that is usually stored in a cookie. The cookie that ASP.NET stores, for example, is named "ASP.NET_SessionId".

    0 讨论(0)
  • 2020-12-24 07:04

    you can probably ping the server via ajax inside javascript. The php file might look something like:

    <?php
    session_start();
    $id = session_id();
    echo $id;
    ?>
    

    This will return you the current session id. Was this what you were looking for.

    0 讨论(0)
  • 2020-12-24 07:06

    you can receive the session id by issuing the following regular expression on document.cookie:

    alert(document.cookie.match(/PHPSESSID=[^;]+/));
    

    in my example the cookie name to store session id is PHPSESSID (php server), just replace the PHPSESSID with the cookie name that holds the session id. (configurable by the web server)

    0 讨论(0)
  • 2020-12-24 07:08

    Yes. As the session ID is either transported over the URL (document.location.href) or via a cookie (document.cookie), you could check both for the presence of a session ID.

    0 讨论(0)
  • 2020-12-24 07:08

    The following can be used to retrieve JSESSIONID:

    function getJSessionId(){
        var jsId = document.cookie.match(/JSESSIONID=[^;]+/);
        if(jsId != null) {
            if (jsId instanceof Array)
                jsId = jsId[0].substring(11);
            else
                jsId = jsId.substring(11);
        }
        return jsId;
    }
    
    0 讨论(0)
提交回复
热议问题