`
icrwen
  • 浏览: 269393 次
  • 性别: Icon_minigender_2
  • 来自: 济南
社区版块
存档分类
最新评论

javascript cookie的删除 保存 读取

    博客分类:
  • JS
阅读更多

you really don't need much knowledge to use this script, it's pretty much plug and play, but we'll explain it's main part and how to use them anyway. If you have specific questions, please post them in our Javascript Forum and we will answer them there.

Set Cookie Javascript Function

You need to put the name and values in quotes when you call the function, like this:
Set_Cookie( 'mycookie', 'visited 9 times', 30, '/', '', '' );. Don't forget to put in empty quotes for the unused parameters or you'll get an error when you run the code. This makes the cookie named 'mycookie', with the value of 'visited 9 times', and with a life of 30 days, and the cookie is set to your root folder.

The Set_Cookie values for 'domain' and 'secure' are not utilized. Use 'domain' on the Javascript cookie if you are using it on a subdomain, like widgets.yoursite.com, where the cookie is set on the widgets subdomain, but you need it to be accessible over the whole yoursite.com domain.

It's good practice to not assume the path to the site root will be set the way you want it by default, so do this manually as a rule, '/'. If no value is set for expires, it will only last as long as the current session of the visitor, and will be automatically deleted when they close their browser.

function Set_Cookie( name, value, expires, path, domain, secure )
{
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

/*
if the expires variable is set, make the correct
expires time, the current script below will set
it for x number of days, to make it for hours,
delete * 24, for minutes, delete * 60 * 24
*/
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
( ( path ) ? ";path=" + path : "" ) +
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}
			

This will set the cookie. It's the most complicated part, but actually for most purposes all you need to set are the first 4 parameters, name, value, expires, and path. If you want the cookie available only in one folder, you will need to add '/folder_name/' as a path variable, that tells the script to set the cookie for the just that path, not for the whole domain.

As a good general rule, set the path to '/', the root of your website. Generally 'domain' and 'secure' are not something you will be needing to use unless you set the cookie on a subdomain, in which case you may want to set the domain to your primary domain if you want it to be accessible from the main domain, or other subdomains.

Get Cookie Javascript Function
// this fixes an issue with the old method, ambiguous values
// with this test document.cookie.indexOf( name + "=" );
function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}
				

Please note that the above version fixes some fairly serious issues with the old version, here listed below for comparison. The original utterly fails to handle cases where cookie names are substrings of other cookies, say like: site_main, site_main2 and so on. Thanks to ThoughtfulCoder for point this problem out. What's amazing to contemplate that this original code has been up for years without anyone noticing that weakness.

// this function gets the cookie, if it exists
// don't use this, it's weak and does not handle some cases
// correctly, this is just to maintain legacy information
function Get_Cookie( name ) {

var start = document.cookie.indexOf( name + "=" );
var len = start + name.length + 1;
if ( ( !start ) &&
( name != document.cookie.substring( 0, name.length ) ) )
{
return null;
}
if ( start == -1 ) return null;
var end = document.cookie.indexOf( ";", len );
if ( end == -1 ) end = document.cookie.length;
return unescape( document.cookie.substring( len, end ) );
}
			

This will retrieve the cookie by name, if the cookie does not exist, it will return false, so you can do things like if ( Get_Cookie( 'your_cookie' ) ) do something.

Delete Cookie Javascript Function
// this deletes the cookie when called
function Delete_Cookie( name, path, domain ) {
if ( Get_Cookie( name ) ) document.cookie = name + "=" +
( ( path ) ? ";path=" + path : "") +
( ( domain ) ? ";domain=" + domain : "" ) +
";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
			

Here all you need to do is put in: Delete_Cookie('cookie name', '/', '') and the cookie will be deleted. Remember to match the cookie name, path, and domain to what you have it in Set_Cookie exactly, or you may get some very hard to diagnose errors.

WARNING: Do not assume the Cookie has actually been deleted during that session, both Opera and IE have in some of their browser versions maintained the cookie until you restart your browser even if you have deleted it in the script. If script functionality depends on the delete action having happened, make sure you do another Get_Cookie test on the deleted cookie to make sure it's actually deleted.

Sample Page Code for Javascript Cookies
<script type="text/javascript">
// remember, these are the possible parameters for Set_Cookie:
// name, value, expires, path, domain, secure
Set_Cookie( 'test', 'it works', '', '/', '', '' );
if ( Get_Cookie( 'test' ) ) alert( Get_Cookie('test'));
// and these are the parameters for Delete_Cookie:
// name, path, domain
// make sure you use the same parameters in Set and Delete Cookie.
Delete_Cookie('test', '/', '');
( Get_Cookie( 'test' ) ) ? alert( Get_Cookie('test')) :
alert( 'it is gone');
</script>
			

If you run this, what will happen is that you will get two alerts, the first one will have the content you set with Set_Cookie, the second will say 'it is gone' since you have now deleted the cookie. That's about it.

 

分享到:
评论

相关推荐

    cookie保存并读取用户登录信息

    3. **Cookie的读取**:在JSP或Servlet中,我们可以通过`HttpServletRequest`对象的`getCookies()`方法获取所有Cookie,然后遍历查找我们需要的Cookie: ```jsp Cookie[] cookies = request.getCookies(); for ...

    Javascript Cookie操作类的封装

    Cookie是由服务器端发送到浏览器并保存在本地的一个小文本文件,它由键值对组成,每个键值对之间用分号(;)隔开。在浏览器下次请求同一域的页面时,会自动将Cookie一起发送回服务器。每个Cookie都有一个生命周期,...

    javascript cookie 操作框架 XCookie

    总结一下,XCookie是一个实用的JavaScript库,用于简化浏览器cookie的管理工作,它提供了一组易于理解和使用的API,涵盖了创建、读取、更新和删除cookie的各种操作。了解和掌握这个框架将有助于提高前端开发的效率,...

    UIWebView的cookie读取与保存

    总结,UIWebView的Cookie读取与保存是iOS应用与Web服务交互中重要的一环。通过NSHTTPCookieStorage和UIWebView的JavaScript接口,开发者可以方便地管理用户的登录状态和其他基于Cookie的信息。然而,随着技术的发展...

    js操作cookie 读取 存取 删除 调用

    通过JavaScript,我们可以非常方便地对Cookie进行读取、存取以及删除等操作。 #### 二、核心功能解析 ##### 1. 读取Cookie 读取Cookie主要是为了获取存储在用户浏览器中的信息。例如,可以通过读取Cookie来判断...

    js中cookie的创建和读取单个cookie值

    js中cookie的创建和读取单个cookie值,以及设置cookie的过期时间。 能够判断是否有自己需要查找的cookie,如果没有查到到就可以执行创建语句

    javascript 对cookie 的读写操作

    javascript对cookie的日常操作

    javascript创建cookie、读取cookie

    JavaScript提供了操作Cookie的原生方法,能够实现创建Cookie和读取Cookie的功能。以下详细知识点将围绕JavaScript中如何创建和读取Cookie来进行深入介绍。 ### 创建Cookie 创建Cookie的基本语法非常简单,只需要对...

    asp.net与javascript混合添加、删除、修改、读取cookie

    本文将深入探讨如何利用这两种技术来实现对cookie的操作,包括添加、删除、修改和读取。 首先,我们要理解cookie的基本概念。Cookie是服务器发送到用户浏览器并存储在本地的一小段文本信息。它用于存储用户状态信息...

    cookie中设置了HttpOnly属性,那么通过js脚本将无法读取到cookie信息,这样能有效的防止XSS攻击.zip_js设置cookie值

    当一个Cookie被设置为HttpOnly时,JavaScript无法通过Document.cookie API或其他方式访问到这个Cookie。这样一来,即使网页中存在XSS漏洞,恶意脚本也无法窃取到包含敏感信息的Cookie,从而降低了攻击者盗取用户身份...

    CookiesjsJavaScript客户端的Cookie操作库

    作为客户端库,它使得开发者无需后端服务器参与就能创建、读取、更新和删除Cookie,增强了前端应用对用户状态的管理能力。 **标签解析:** "JavaScript开发-其它杂项" 暗示了Cookies.js是JavaScript开发工具的一...

    jquery.cookie.js 以及用法 cookie读取与存储

    在Web开发中,Cookie是一种常用的数据存储机制,它允许我们在用户浏览器端保存少量信息。`jquery.cookie.js`是jQuery的一个扩展插件,为开发者提供了简单易用的API来操作Cookie。本文将详细探讨`jquery.cookie.js`的...

    C#和javascript操作cookie

    总结起来,C#和JavaScript在处理Cookie时各有其特点:C#在服务器端创建和管理Cookie,而JavaScript在客户端进行读取、修改和删除操作。这种协同工作模式在许多Web应用中都十分常见,尤其在需要进行用户状态追踪和...

    javascript cookie用法基础教程(概念,设置,读取及删除)

    三、使用 JavaScript 设置、读取和删除 Cookie 设置 Cookie 使用 `document.cookie` 属性。例如: ```javascript document.cookie = 'username=abc'; document.cookie = 'password=123'; document.cookie = 'email=...

    Net Cookie操作读取数据

    可以通过设置HttpOnly属性防止JavaScript访问Cookie,以降低XSS攻击风险;设置Secure属性确保Cookie只在HTTPS连接中传输,增加安全性。 七、Cookie管理最佳实践 1. 限制Cookie大小:每个Cookie的大小不应超过4KB,...

    javascript 中Cookie读、写与删除操作.docx

    本文将详细介绍如何在JavaScript中进行Cookie的读取、写入及删除操作,并探讨一些高级主题如跨域问题。 #### Cookie的基本概念 Cookie是一种小型文本文件,由服务器发送给客户端浏览器,浏览器会将Cookie保存起来...

    用JS设置、读取、删除cookie

    本文将详细介绍如何使用JavaScript来设置、读取和删除Cookie。 #### Cookie简介 Cookie是由服务器发送到客户端的一小段文本信息,并且保存在用户的计算机上,通过浏览器再发送回服务器。它主要用于跟踪用户的会话...

    javascript实现cookie功能

    在这个Java工程中,尽管主要编程语言是Java,但JavaScript用于前端页面与用户的交互,包括创建、读取和删除Cookie。 首先,我们需要理解Cookie的基本概念。一个Cookie由名称、值、过期时间、路径和域等属性组成。...

    JavaScript Cookie的读取和写入函数

    JavaScript Cookie的读取和写入函数可以实现Cookie的读取、写入、删除等操作。 setcookie函数 setcookie函数是设置Cookie的通用函数,该函数需要至少一个参数name,其他参数为可选参数。setcookie函数的实现如下所...

    JS读取cookie(记住账号密码)

    - `secure`:如果存在此属性,则只有在HTTPS安全连接下才可读取此cookie。 获取cookie的方法通常涉及到字符串的解析,因为`document.cookie`返回的是一个字符串,其中包含所有cookie的信息。示例代码如下: ```...

Global site tag (gtag.js) - Google Analytics