7.11. 解析Javascript中的setCookie为Cookie变量:parseJsSetCookie
//parse Javascript string "$Cookie.setCookie(XXX);" to a cookie
// input example:
//$Cookie.setCookie('wla42','cHJveHktYmF5LnB2dC1jb250YWN0cy5tc24uY29tfGJ5MioxLDlBOEI4QkY1MDFBMzhBMzYsMSwwLDA=','live.com','/',new Date(1328842189083.44),1);
//$Cookie.setCookie('wla42','YnkyKjEsOUE4QjhCRjUwMUEzOEEzNiwwLCww','live.com','/',new Date(1329198041411.84),1);
//$Cookie.setCookie('wla42', 'YnkyKjEsOUE4QjhCRjUwMUEzOEEzNiwwLCww', 'live.com', '/', new Date(1329440307389.9), 1);
//$Cookie.setCookie('wla42', 'cHJveHktYmF5LnB2dC1jb250YWN0cy5tc24uY29tfGJ5MioxLDlBOEI4QkY1MDFBMzhBMzYsMSwwLDA=', 'live.com', '/', new Date(1329440307483.5), 1);
//$Cookie.setCookie('wls', 'A|eyJV-t:a*nS', '.live.com', '/', null, 1);
//$Cookie.setCookie('MSNPPAuth','','.live.com','/',new Date(1327971507311.9),1);
public bool parseJsSetCookie(string singleSetCookieStr, out Cookie parsedCk)
{
bool parseOK = false;
parsedCk = new Cookie();
string name = "";
string value = "";
string domain = "";
string path = "";
string expire = "";
string secure = "";
// 1=name 2=value 3=domain 4=path 5=expire 6=secure
string setckP = @"\$Cookie\.setCookie\('(\w+)',\s*'(.*?)',\s*'([\w\.]+)',\s*'(.+?)',\s*(.+?),\s*(\d?)\);";
Regex setckRx = new Regex(setckP);
Match foundSetck = setckRx.Match(singleSetCookieStr);
if (foundSetck.Success)
{
name = foundSetck.Groups[1].ToString();
value = foundSetck.Groups[2].ToString();
domain = foundSetck.Groups[3].ToString();
path = foundSetck.Groups[4].ToString();
expire = foundSetck.Groups[5].ToString();
secure = foundSetck.Groups[6].ToString();
// must: name valid and domain is not null
if (isValidCookieName(name) && (domain != ""))
{
parseOK = true;
parsedCk.Name = name;
parsedCk.Value = value;
parsedCk.Domain = domain;
parsedCk.Path = path;
// note, here even parse expire field fail
//do not consider it must fail to parse the whole cookie
if (expire.Trim() == "null")
{
// do nothing
}
else
{
DateTime expireTime;
if (parseJsNewDate(expire, out expireTime))
{
parsedCk.Expires = expireTime;
}
}
if (secure == "1")
{
parsedCk.Secure = true;
}
else
{
parsedCk.Secure = false;
}
}//if (isValidCookieName(name) && (domain != ""))
}//foundSetck.Success
return parseOK;
}
例 7.11. parseJsSetCookie 的使用范例