You want to use the following...
var session = <%=Session["username"] != null ? "true" : "false"%>;
Now for as to why you would want to do this is beyond me? If you can check this when the page is being processed on the server you can simply force a redirect like the following...
if(Session["username"] == null) {
Response.Redirect("login.aspx", true);
}
But i'm assuming this is also not what your after. If you want to check the users session is valid repeatedly e.g every 30 seconds then neither of those methods will work.
The reason being is that once the server has sent the page to the user the session check is calculated and hard-coded into the JavaScript. It will NOT be re-assessed everytime you call the javascript method as it is static.
To perform this you will need two steps, the first is to setup a page to return a flag indicating whether a users session is valid and secondly perform an asynchronous request to fetch the users session state.
First of all create a page e.g. SessionCheck.aspx and add the following...
{"valid":<%=Session["username"] != null ? "true" : "false" %>}
Secondly add the following script to your existing page...
function checkSession() {
var request = false;
if(window.XMLHttpRequest) { // Mozilla/Safari
request = new XMLHttpRequest();
} else if(window.ActiveXObject) { // IE
request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.open('POST', 'SessionCheck.aspx', true);
request.onreadystatechange = function() {
if(request.readyState == 4) {
var session = eval('(' + request.responseText + …