How to work with session cookies in IE
Perhaps lots of people bumped thier heads in walls while trying to work with cookies (client side).
I know that server side there are a lot of nice classes but what do we do with the poor people writing JavaScript or C# client side?
So here are some of the things that I done to help in my work:
Get all cookies from document.cookie:
Dictionary<string, string> ret = new Dictionary<string, string>();
if( !string.IsNullOrEmpty( doc.cookie ) )
foreach( string strCookie in doc.cookie.Split( ';' ) )
{
int delimiterPos = strCookie.IndexOf( '=' );
if( -1 != delimiterPos )
{
string strName = strCookie.Substring( 0 , delimiterPos );
string strVal = strCookie.Substring( delimiterPos + 1 );
ret.Add( strName , strVal );
}
else
ret.Add( strCookie , null );
}
return ret;
- this will also work for strange cookies (like with no value ";samename;..." or with multiple "=" ";coo=boo=foo;..."
Delete a cookie:
DateTime dExpire = DateTime.Now;
dExpire = dExpire.Subtract( new TimeSpan( 365*10 , 0 , 0 , 0 ) );
System.Globalization.DateTimeFormatInfo dtfi = new System.Globalization.DateTimeFormatInfo();
if( null == sDomain )
doc.cookie = sCookie + "=;expires=" + dExpire.ToString( "r" , dtfi );
else
doc.cookie = sCookie + "=;expires=" + dExpire.ToString( "r" , dtfi ) +";domain=" + sDomain ;
- just set the expiration date in the past and the cookie is deleted (careful to delete from the same domain as you created the cookie)
Set a cookie:
DeleteCookie( doc , sCookie , sDomain );
if( null == sDomain )
doc.cookie = sCookie + "=" + sNewValue ;
else
doc.cookie = sCookie + "=" + sNewValue + ";domain=" + sDomain ;
return doc.cookie;
- delete the cookie and set it again (or you could just change the value)
How to get the domain from where the cookie was set?
Hmm... that's somehting that I didn't find out yet :(. If you know just leave a comment and I'll incorporate it here.
I will post some more when I find out how to get the domain of a cookie from IE
Thanks,
Ionutz