JavaScript是一门Web编程语言,用来实现网页的交互功能,它和HTML、CSS共同组成了个Web开发的基础工具集合,也是前端开发者必备的技能;学习JavaScript教程可以了解它在网页开发中的所有特性和相关概念,让我们能够更加快速的去开发Web应用。
JavaScript Cookies是在浏览器中保存用户偏好的一种绝佳方式。只要不被用于窃取隐私,这对网站和用户来说都是有益的。
什么是Cookies?
Cookie是由网页浏览器存储在访客计算机中的一小段文本信息。由于数据被保存在硬盘驱动器上,即使计算机关闭后仍可在之后访问该信息。
Cookie可用于身份验证、会话跟踪、记住用户特定信息,如其姓名、密码、最后访问日期等。
Cookie 作为简单的文本片段,本身不可执行。在 JavaScript 中,可通过 document 对象的 cookie 属性创建和读取 Cookie 数据。
您可通过将document.cookie设置为Cookie字符串来配置Cookie。后续我们将详细讨论如何创建及获取Cookie的具体实现细节。
Cookie无法实现哪些功能?
JavaScript:设置 Cookies
Cookies 文本文件(cookies.txt):
在浏览会话期间,浏览器会将Cookie存储于内存中;而在退出时,这些Cookie会被保存至名为cookies.txt的文件。不同浏览器将该Cookie文件存放在磁盘上的不同位置。
以Windows 2000系统为例,Firefox浏览器将Cookie存储在路径C:\Documents and Settings\您的登录名\LocalSettings\ApplicationData\Mozilla\Firefox\Profiles\default .7g1\Cache下。请注意,"default.7g1"文件夹名称可能因您使用的Firefox版本不同而有所变化。每次打开浏览器时,系统会从存储位置读取Cookie;关闭浏览器时,Cookie将被重新保存至磁盘。当Cookie过期后,将不再保留至硬盘。
Cookie包含六个组成部分:名称、值、过期时间、路径、域和安全性。前两个部分即名称和值为必选项,其余部分为可选项。
语法说明
document.cookie="NAME=VALUE; expires=DATE; path=PATH; domain=DOMAIN; secure";
执行一下上述语法的不同组成部分均配有对应标题进行详述。
名称与值
Cookie字符串的第一部分必须包含名称和值。整个名称/值必须为不含逗号、分号或空格字符的单个字符串。以下示例展示了如何将字符串"George"存储到名为'myName'的Cookie中,对应的JavaScript语句为:
document.cookie = "myName=George";
使用encodeURIComponent()和decodeURIComponent()函数。
通过使用encodeURIComponent()函数,可以确保Cookie值字符串不包含任何逗号、分号或空格字符,这些字符在Cookie值中是不允许的。
encodeURIComponent("Good Morning");
返回字符串为:
Good%20Morning
当解码decodeURIComponent("Good%20Morning")时,字符串被解析为:Good Morning
早上好。
过期时间:expires
Cookie的生命周期极为有限。当用户退出浏览器时,Cookie将自动失效。若需延长Cookie的有效期,必须按照以下格式设置过期时间。
日-月缩写-年 时:分:秒 GMT(DD-Mon-YY HH:MM:SS GMT)
这是一个Cookie有效期截至Mon, 12 Jun 2011:00:00:00 GMT的示例。
document.cookie = "VisiterName=George; expires=Mon, 12 Jun 2011:00:00:00 GMT; ";
在上述示例中,我们在页面中硬编码了日期,但在实际应用中,您可以使用Date对象获取当前日期,然后将Cookie的过期时间设置为六个月或十个月。
示例如下
cookieExpire = new Date();
cookieExpire.setMonth(cookieExpire.getMonth() + 10);
document.cookie = "VisitorName=George; expires="+ expireDate.toGMTString() + ";";
执行一下上述JavaScript代码将创建一个名为VisitorName的新Cookie,其值设为'George',该Cookie会在当前日期起10个月后失效。
路径(path)
若页面www.w3capi.com/javascript/设置了cookie,则该目录(即../javascript)及其子目录下的所有页面均可读取该cookie。但www.w3capi/php/目录下的页面无法读取此cookie。通常路径(path)被设置为根目录('/'),这意味着cookie对整个站点的所有页面都可用。若要使cookie在名为php的特定目录中可读,需添加path=/php;参数。
此示例中设置了一个名为"php"的特定路径
在以下代码中,我们指定了该Cookie对该域的所有子目录均可用。
域名:domain
若网站拥有多个子域,'domain'参数可使cookie对其他子域生效。例如门户网站'mysite':主站http://www.mysite.com下设婚恋站(http://matimonial.mysite.com)、金融站(http://financial.mysite.com)和旅行站(http://travel.mysite.com)。默认情况下,旅行站设置的cookie金融站无法读取。但添加domain=mysite.com参数后,所有以'mysite.com'结尾的域名均可读取该cookie。需注意域名必须至少包含两个点(.),如".mysite.com"。
示例如下。
document.cookie= "VisiterName=George;expires=Mon,12Jun2011:00:00:00"
+ ";path=/" + domain = mysite.com;";
执行一下安全性:Secure
cookie字符串的最后一个部分是安全属性,该属性为布尔值。默认值为false。若cookie被标记为安全(即secure值设为true),则该cookie仅会通过安全通信通道发送至Web服务器并进行检索。此属性适用于具备SSL(Secure Sockets Layer)功能的服务器。
JavaScript:创建Cookies
我们已经学习了Cookie的各个组成部分,如名称、值、到期时间、路径、域名和安全属性。现在让我们创建一个简单的Cookie。
在以下示例中,我们编写了一个名为'CookieSet'的函数并设置其部分属性。
示例:
在以下网络文档中,四个参数name(名称)、value(值)、expires(有效期)和path(路径)被传递给CookieSet函数。secure(安全)和domain(域)参数在此场景中非必要。当expires和path参数接收空值时存在校验逻辑:若expires参数为空,则自动设置为当前日期后推9个月的到期时间;若path参数为空,则默认路径设为当前目录及其子目录。toUTCString方法将日期转换为符合通用时间格式(GMT)的字符串表示。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<title>JavaScript creating cookies - example1</title>
</head>
<body>
<h1 style="color: red">JavaScript creating cookies - example1</h1>
<hr />
<script type="text/javascript">
//This is done to make the following JavaScript code compatible to XHTML. <![CDATA[
function CookieSet (cName, cValue, cPath, cExpires)
{
cvalue = encodeURIComponent(cValue);
if (cExpires == "")
{
var cdate = new Date();
cdate.setMonth(cdate.getMonth() + 9);
cExpires = cdate.toUTCString();
}
if (cPath != "")
{
cPath = ";Path=" + cPath;
}
document.cookie = cName + "=" + cValue +"expires=" + cExpires + cPath;
}
CookieSet("Name","George ","","");
alert(document.cookie)
//]]>
</script>
</body>
</html>
执行一下示例:接收用户真实数据并存储至Cookie中。
以下网页文档接收来自用户的真实数据并将其存储于Cookie中,存储时长为自当前日期起一年。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<title>JavaScript creating cookies - receive real data. example1</title>
</head>
<body>
<h1 style="color: red">JavaScript creating cookies, receive real data. - example1</h1>
<hr />
<script type="text/javascript">
//This is done to make the following JavaScript code compatible to XHTML. <![CDATA[
var visitor_name = prompt("What's your name?","");
var expr_date = new Date("December 30, 2012");
var cookie_date = expr_date.toUTCString();
final_cookie = "Name =" + encodeURIComponent(visitor_name) + ";expires_on = " + cookie_date;
document.cookie = final_cookie;
alert(final_cookie);
//]]>
</script>
</body>
</html>
执行一下删除Cookie
删除Cookie的操作极为简单。要删除某个Cookie,首先需获取其名称并创建同名Cookie,将有效期设置为当前日期的前一天。由于有效期已过期,浏览器会立即清除该Cookie。无法保证在当前会话期间该Cookie已被删除,部分浏览器会保留该Cookie直至重启浏览器。具体示例请查阅:Cookies实战案例。
JavaScript:读取Cookie
当浏览器打开网页时,该浏览器会读取存储于您计算机上的Cookie(前提是该浏览器已存储了这些Cookie)。我们使用document.cookie方法来检索与Cookie相关的信息。
示例:
在以下网页文档中,我们从访客处接收名称并存储于名为“Name”的cookie中。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<title>JavaScript creating cookies - receive real data. example1</title>
</head>
<body>
<h1 style="color: red">JavaScript creating cookies, receive real data. - example1</h1>
<hr />
<script type="text/javascript">
//This is done to make the following JavaScript code compatible to XHTML. <![CDATA[
var visitor_name = prompt("What's your name?","");
var curdate = new Date();
curdate.setMonth(curdate.getMonth() + 6);
var cookie_date = curdate.toUTCString();
final_cookie = "my_cookie=" + encodeURIComponent(visitor_name) + ";expires_on = " + cookie_date;
document.cookie = final_cookie;
alert(final_cookie);
//]]>
</script>
</body>
</html>
执行一下示例:从Cookie中获取值
在以下网页文档中,我们将读取存储的Cookie并获取其值。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<title>JavaScript : Retrieve values from a cookie - example1</title>
</head>
<body>
<h1 style="color: red">JavaScript : Retrieve values from a cookie - example1</h1>
<hr />
<script type="text/javascript">
//This is done to make the following JavaScript code compatible to XHTML. <![CDATA[
var search_cookie = "my_cookie" + "="
if (document.cookie.length > 0)
{
// Search for a cookie.
offset = document.cookie.indexOf(search_cookie)
if (offset != -1)
{
offset += search_cookie.length
// set index of beginning of value
end = document.cookie.indexOf(";",offset)
if (end == -1)
{
end = document.cookie.length
}
alert(decodeURIComponent(document.cookie.substring(offset, end)))
}
}
//]]>
</script>
</head>
</body>
</html>
执行一下JavaScript Cookies 真实示例
在以下网页文档中,若访客提交了姓名,当其在此后的九个月内再次访问该页面时,其姓名将被显示。当访客提交姓名时,系统会在其硬盘中存储一个Cookie,要删除此Cookie请参阅下一示例。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<title>JavaScript Cookie</title>
<script type="text/javascript">
//This is done to make the following JavaScript code compatible to XHTML. <![CDATA[
function register(name)
{
var curdate = new Date();
curdate.setMonth(curdate.getMonth() + 9);
cookieExpires = curdate.toUTCString();
final_cookie = "mycookie=" + encodeURIComponent(name) + ";expires_on = " + cookieExpires;
document.cookie = final_cookie;
}
function getCookie(cookie_name)
{
var search_cookie = cookie_name + "="
if (document.cookie.length > 0)
{
start_position = document.cookie.indexOf(search_cookie)
if (start_position!= -1)
{
start_position += search_cookie.length
end_position = document.cookie.indexOf(";", start_position)
if (end_position == -1)
end_position = document.cookie.length
return (decodeURIComponent(document.cookie.substring(start_position, end_position)))
}
}
}
//]]>
</script>
</head>
<body>
<h1 style="color: red">JavaScript Cookie</h1>
<hr />
<script type="text/javascript">
//This is done to make the following JavaScript code compatible to XHTML. <![CDATA[
var username = getCookie("mycookie")
if (username)
{
document.write("Welcome Back, ", username)
}
if (username == null)
{
document.write("You haven't been here in the last nine months...")
document.write("When you return to this page in next nine months, ");
document.write("your name will be displayed...with Welcome.");
document.write('<form onsubmit = "return false">');
document.write('<p>Enter your name: </p>');
document.write('<input type="text" name="username" size="40">');
document.write('<input type = "button" value= "Register"');
document.write('onClick="register(this.form.username.value); history.go(0)">');
document.write('</form>');
}
//]]>
</script>
</body>
</html>
执行一下要从硬盘中删除上述Cookie,请使用以下网页文档。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<title>JavaScript Cookie - example1</title>
<script type="text/javascript">
//This is done to make the following JavaScript code compatible to XHTML. <![CDATA[
function register(name)
{
var nowDate = new Date();
nowDate.setMonth(nowDate.getMonth() + 9);
cookieExpires = nowDate.toUTCString();
final_cookie = "mycookie=" + encodeURIComponent(name) + ";expires_on = " + cookieExpires;
document.cookie = final_cookie;
}
function getCookie(cookie_name)
{
var search_cookie = cookie_name + "="
if (document.cookie.length > 0)
{
start_position = document.cookie.indexOf(search_cookie)
if (start_position!= -1)
{
start_position += search_cookie.length
end_position = document.cookie.indexOf(";", start_position)
if (end_position == -1)
end_position = document.cookie.length
return (decodeURIComponent(document.cookie.substring(start_position, end_position)))
}
}
}
//]]>
</script>
</head>
<body>
<h1 style="color: red">JavaScript Cookie - example1</h1>
<hr />
<script type="text/javascript">
//This is done to make the following JavaScript code compatible to XHTML. <![CDATA[
var yourname = getCookie("mycookie")
if (yourname)
{
document.write("Welcome Back, ", yourname)
}
if (yourname == null)
{
document.write("You haven't been here in the last nine months...")
document.write("When you return to this page in next nine months, ");
document.write("your name will be displayed...with Welcome.");
document.write('<form onsubmit = "return false">');
document.write('<p>Enter your name: </p>');
document.write('<input type="text" name="username" size="40">');
document.write('<input type = "button" value= "Register"');
document.write('onClick="register(this.form.username.value); history.go(0)">');
document.write('</form>');
}
//]]>
</script>
</body>
</html>
执行一下