SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Hybrid View

  1. #1
    SitePoint Zealot Cheeser's Avatar
    Join Date
    Nov 2003
    Location
    Washington, DC
    Posts
    126
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Cookie Detection

    Well, I searched and I couldn't find anything that I needed, so:

    I currently have a site which uses cookies, the problem is that I want it to detect if the browser being used has cookies enabled. I know you can accomplish this by setting a cookie in JavaScript and testing for it (i don't know how to do it, though), *BUT* I need the script to be compliant with all (or at least most) browsers. By this I mean, Mozilla, Firebird, Opera, IE, Netscape, and anything else you can think of. Ok, thanks in advance

  2. #2
    SitePoint Enthusiast
    Join Date
    Nov 2002
    Posts
    51
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Here's some cross-browser cookie code...

    Code:
    var Cookie = {};
    Cookie.set = function(name,value,days){
    	if(days){
    		var date = new Date();
    		date.setTime(date.getTime()+(days*24*60*60*1000));
    		var expires = "; expires="+date.toGMTString();
    	}else{
    		var expires = "";
    	}
    	document.cookie = name+"="+value+expires+"; path=/";
    }
    Cookie.get = function(name){
    	name += "=";
    	var s = document.cookie.split("; ");
    	for(var i = 0; i < s.length; i++){
    		var c = s[i];
    		if(c.indexOf(name) == 0){
    			return unescape(c.substring(name.length,c.length));
    		}
    	}
    	return null;
    }
    Cookie.erase = function(name){
    	this.set(name,"",-1);
    }
    Cookie.isEnabled = function(){
    	this.set("cookietest","cookietest");
    	return this.get("cookietest") != null;
    }
    ...and here's an example of how to test if cookies are enabled.

    Code:
    if(Cookie.isEnabled()){
    	var count = Cookie.get("countCookie");
    	count = count ? parseInt(count)+1 : 0;
    	Cookie.set("countCookie",count,365);
    	document.write("<p>You have visited this page "+count+" times.<\/p>");
    }else{
    	document.write("<p>Your cookies are disabled.<\/p>");
    }
    travis

  3. #3
    SitePoint Zealot Cheeser's Avatar
    Join Date
    Nov 2003
    Location
    Washington, DC
    Posts
    126
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank you!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •