Home > Web Front-end > JS Tutorial > body text

JavaScript operation cookie method function collection

PHP中文网
Release: 2016-05-16 18:23:40
Original
1385 people have browsed it

Question:
Enables you to keep the last settings when accessing a page, or share data between different pages. For example, if a user sets the font size of a page when visiting a website, he or she hopes that the same setting can be used for browsing the next time the user visits the website without having to set it again.
Solution:
When the user browses the page and makes settings, save these settings in a cookie, and read the settings in the cookie the next time he visits.
Refer to the following script:

// utility function to retrieve an expiration data in proper format; 
function getExpDate(days, hours, minutes) 
{ 
var expDate = new 
Date(); 
if(typeof(days) == "number" && typeof(hours) == "number" 
&& typeof(hours) == "number") 
{ 
expDate.setDate(expDate.getDate() + parseInt(days)); 
expDate.setHours(expDate.getHours() + parseInt(hours)); 
expDate.setMinutes(expDate.getMinutes() + parseInt(minutes)); 
return 
expDate.toGMTString(); 
} 
} 
//utility function called by getCookie() 
function getCookieVal(offset) 
{ 
var endstr = 
document.cookie.indexOf(";", offset); 
if(endstr == -1) 
{ 
endstr = 
document.cookie.length; 
} 
return 
unescape(document.cookie.substring(offset, endstr)); 
} 
// primary 
function to retrieve cookie by name 
function getCookie(name) 
{ 
var 
arg = name + "="; 
var alen = arg.length; 
var clen = 
document.cookie.length; 
var i = 0; 
while(i < clen) 
{ 
var j = 
i + alen; 
if (document.cookie.substring(i, j) == arg) 
{ 
return 
getCookieVal(j); 
} 
i = document.cookie.indexOf(" ", i) + 1; 
if(i == 
0) break; 
} 
return; 
} 
// store cookie value with optional 
details as needed 
function setCookie(name, value, expires, path, domain, 
secure) 
{ 
document.cookie = name + "=" + escape(value) + 
((expires) 
? "; expires=" + expires : "") + 
((path) ? "; path=" + path : "") + 
((domain) ? "; domain=" + domain : "") + 
((secure) ? "; secure" : ""); 
} 
// remove the cookie by setting ancient expiration date 
function 
deleteCookie(name,path,domain) 
{ 
if(getCookie(name)) 
{ 
document.cookie = name + "=" + 
((path) ? "; path=" + path : "") + 
((domain) ? "; domain=" + domain : "") + 
"; expires=Thu, 01-Jan-70 
00:00:01 GMT"; 
} 
}
Copy after login

Use the getCookie(name) function to read the value saved in the cookie. The parameter name is the name of the cookie item. If the cookie item does not exist, an empty string is returned.
Use the setCookie() function to save the value of the cookie item, where the first and second parameters are the name and value of the cookie item respectively. If you want to set an expiration time for it, you need to set the third parameter. Here you need to get a parameter in the correct format through getExpDate().
Finally, use deleteCookie() to delete an existing cookie item, essentially by letting the item expire.
Cookies save data on the client side. The script of the page can only read the cookie value of the domain and server. If there are multiple servers in the domain, you need to set the fifth parameter to specify the server. The capacity of the browser is generally limited to 20 name/value pairs per server, and each cookie item should not exceed 4,000 characters. More realistically, a single cookie item should be less than 2,000 characters, which means do not use cookies to save large cookies on the client. capacity data.
Different browsers save cookies in different ways. IE creates a text file for each domain's cookies, while Netscape stores all cookies in the same text file.
Note: Cookies are stored on the client side, so they will be affected by browser settings. For example, users may disable cookies. To detect whether your browser supports cookies, use the navigator.cookieEnabled property.

<script> 
//写cookies函数 作者:翟振凯 
function 
SetCookie(name,value)//两个参数,一个是cookie的名子,一个是值 
{ 
var Days = 30; //此 
cookie 将被保存 30 天 
var exp = new Date(); //new Date("December 31, 9998"); 
exp.setTime(exp.getTime() + Days*24*60*60*1000); 
document.cookie = name 
+ "="+ escape (value) + ";expires=" + exp.toGMTString(); 
} 
function 
getCookie(name)//取cookies函数 
{ 
var arr = document.cookie.match(new 
RegExp("(^| )"+name+"=([^;]*)(;|$)")); 
if(arr != null) return 
unescape(arr[2]); return null; 
} 
function delCookie(name)//删除cookie 
{ 
var exp = new Date(); 
exp.setTime(exp.getTime() - 1); 
var 
cval=getCookie(name); 
if(cval!=null) document.cookie= name + 
"="+cval+";expires="+exp.toGMTString(); 
} 
SetCookie ("xiaoqi", "3") 
alert(getCookie(&#39;xiaoqi&#39;)); 
</script>
Copy after login

A very practical javascript function for reading and writing cookies

function GetCookieVal(offset) 
//获得Cookie解码后的值 
{ 
var endstr = 
documents.cookie.indexOf (";", offset); 
if (endstr == -1) 
endstr = 
documents.cookie.length; 
return unescape(documents.cookie.substring(offset, 
endstr)); 
} 
function SetCookie(name, value) 
//设定Cookie值 
{ 
var expdate = new Date(); 
var argv = SetCookie.arguments; 
var argc = 
SetCookie.arguments.length; 
var expires = (argc > 2) ? argv[2] : null; 
var path = (argc > 3) ? argv[3] : null; 
var domain = (argc > 4) ? 
argv[4] : null; 
var secure = (argc > 5) ? argv[5] : false; 
if(expires!=null) expdate.setTime(expdate.getTime() + ( expires * 1000 )); 
documents.cookie = name + "=" + escape (value) +((expires == null) ? "" : 
("; expires="+ expdate.toGMTString())) 
+((path == null) ? "" : ("; path=" + 
path)) +((domain == null) ? "" : ("; domain=" + domain)) 
+((secure == true) 
? "; secure" : ""); 
} 
function DelCookie(name) 
//删除Cookie 
{ 
var exp = new Date(); 
exp.setTime (exp.getTime() - 1); 
var cval = 
GetCookie (name); 
documents.cookie = name + "=" + cval + "; expires="+ 
exp.toGMTString(); 
} 
function GetCookie(name) 
//获得Cookie的原始值 
{ 
var arg = name + "="; 
var alen = arg.length; 
var clen = 
documents.cookie.length; 
var i = 0; 
while (i < clen) 
{ 
var j 
= i + alen; 
if (documents.cookie.substring(i, j) == arg) 
return 
GetCookieVal (j); 
i = documents.cookie.indexOf(" ", i) + 1; 
if (i == 0) 
break; 
} 
return null; 
} 

<SCRIPT language="javascript"> 
<!-- 
function openpopup(){ 
url="popup.htm" 
window.open("gonggao.htm","gonggao","width=260,height=212,left=200,top=0") 
} 
function get_cookie(Name) { 
var search = Name + "=" 
var 
returnvalue = ""; 
if (documents.cookie.length > 0) { 
offset = 
documents.cookie.indexOf(search) 
if (offset != -1) { 
offset += 
search.length 
end = documents.cookie.indexOf(";", offset); 
if (end == 
-1) 
end = documents.cookie.length; 
returnvalue=unescape(documents.cookie.substring(offset, end)) 
} 
} 
return returnvalue; 
} 
function helpor_net(){ 
if 
(get_cookie(&#39;popped&#39;)==&#39;&#39;){ 
openpopup() 
documents.cookie="popped=yes" 
} 
} 
helpor_net() 
//--> 
</SCRIPT>
Copy after login

If you click OK, as long as you don’t know the cookie, you will not be prompted again for future visits. If you don’t click OK, It will prompt every time. Place it in a js file, and the entire site contains

<SCRIPT LANGUAGE="JavaScript"> 
<!-- 
var the_cookie = 
document.cookie; 
var broken_cookie = the_cookie.split(":"); 
var 
the_visiteraccepted = unescape(broken_cookie[1]); 
// 
if 
(the_visiteraccepted=="undefined"){ 
var tmp=confirm(&#39;中国人何时何地。&#39;); 
if(tmp==false){ 
window.close(); 
}else{ 
var the_visiteraccepted = 
1; 
var the_cookie = "ILoveChina=visiteraccepted:" + 
escape(the_visiteraccepted); 
document.cookie = the_cookie; 
} 
} 
//--> 
</SCRIPT>
Copy after login

1. Cookie compatibility issues
Cookie format has 2 different versions, the first version is called Cookie Version 0, was originally developed by Netscape and is supported by almost all browsers. The newer version, Cookie Version 1, is based on RFC 2109 document. In order to ensure compatibility, JAVA stipulates that the operations involving cookies mentioned above are performed for older versions of cookies. The new version of Cookie is currently not supported by the Javax.servlet.http.Cookie package.
2. Cookie content
The character limits of the same cookie content are different for different cookie versions. In Cookie Version 0, some special characters, such as spaces, square brackets, parentheses, equal signs (=), commas, double quotes, slashes, question marks, @ symbols, colons, and semicolons cannot be used as cookie content. This is why we set the cookie content to "Test_Content" in the example.
Although in Cookie Version 1 regulations have relaxed the restrictions and these characters can be used, but considering that the new version of the Cookie specification is still not supported by all browsers, to be on the safe side, we should try to avoid using these characters in the content of Cookies

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template