Is it by any means possible to read the browser session id using javascript?
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.
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".
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.
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)
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.
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;
}