google+javascriptbanktwitter@js_bankfacebook@jsbankrss@jsbank






Cookie và JavaScript: Làm sao để dùng Theo định nghĩa của Wikipedia: "Cookie là các thông tin lưu trong máy tính thường được dùng để nhận ra người dùng khi viếng thăm một trang web. Nó là những tập tin mà trang web gửi đến máy tính của người dùng". Kể từ khi ra đời đến nay, hầu như cookie như đã trở thành một nhân tố không thể thiếu với bất kì một ứng dụng web hay trình duyệt nào.

Nếu vẫn còn mơ hồ với cookie và việc sử dụng nó với JavaScript thì bài viết này có lẽ phù hợp với bạn. Thông qua bài viết này, bạn sẽ nắm vững được cách dùng JavaScript để tạo, lưu trữ và truy xuất cookie.


Nhãn: Cookie, tập tin, nhân tố, ứng dụng web, lưu trữ, truy xuất

Miễn phí web hosting 1 năm đầu tại iPage



Nếu bạn vẫn còn đang tìm kiếm một nhà cung cấp hosting đáng tin cậy, tại sao không dành chút thời gian để thử với iPage, chỉ với không quá 40.000 VNĐ/tháng, nhưng bạn sẽ được khuyến mãi kèm với quà tặng trị giá trên 10.000.0000 VNĐ nếu thanh toán cho 24 tháng ~ 900.000 VNĐ?

Có trên 1 triệu khách hàng hiện tại của iPage đã & đang hài lòng với dịch vụ, tuyệt đối chắc chắn bạn cũng sẽ hài lòng giống họ! Quan trọng hơn, khi đăng ký sử dụng web hosting tại iPage thông qua sự giới thiệu của chúng tôi, bạn sẽ được hoàn trả lại toàn bộ số tiền bạn đã sử dụng để mua web hosting tại iPage. Wow, thật tuyệt vời! Bạn không phải tốn bất kì chi phí nào mà vẫn có thể sử dụng miễn phí web hosting chất lượng cao tại iPage trong 12 tháng đầu tiên. Chỉ cần nói chúng tôi biết tài khoản của bạn sau khi đăng ký.

Nếu muốn tìm hiểu thêm về ưu / nhược điểm của iPage, bạn hãy đọc đánh giá của ChọnHostViệt.com nhé!
Thử iPage miễn phí cho năm đầu tiên NGAY

This is my very first weekly tips for web design and development. From now on, I'll be posting it every week, and will cover all sort of interesting, helpful web design and development tips and tricks.

"In computing, a cookie (also tracking cookie, browser cookie, and HTTP cookie) is a small piece of text stored on a user's computer by a web browser. A cookie consists of one or more name-value pairs containing bits of information such as user preferences, shopping cart contents, the identifier for a server-based session, or other data used by websites." - Wikipedia - HTTP Cookie

Relates:
- Cookies in JavaScript
- JavaScript Delicious Cookies
- JavaScript Cookie Enabled script

Yes, we'll look into how to manipulate cookies using Javascript. Just in case f you have no ideas what cookies can do, below are the two major usages:

  • Store authentication/session: Have you notice that remember me checkbox under the login box? It uses cookie to remember you. It stores your session details so that you don't have to login when you visit the website again.
  • Store data: You can use cookie to store data in client's computer. For example, Displaying a "welcome back" message or automatically fill in the username field. Or you can use it to remember the position of the current selected menu item, selected tab or position of elements
Advantages
  • Cookies do not use server resources since it stores in client's computer.
  • Expiry date of cookies can be configured.
  • Easy to implement.
Diadvantages
  • Users can delete a cookies.
  • Browsers can be set to decline cookies (By default, all browsers accept cookies).
  • Cookie stores data in plain text thus a potential security threat.
  • It can store huge amount of data

Create, Modify and Erase Cookie

We have to understand how it works before we can go further, the structure of cookie is simple, it's made of:

  1. Name-value pair which stores the data.
  2. Expiry date, after which time the entry will be deleted.
  3. Web domain and path that the cookie should be associated with.
/* assume today date is 2009-09-09 */
/* Create a cookie that will expire 2 days later */
document.cookie = "name=kevin; expires=Fri, 11-Sep-2009 23:59:59 GMT; path=/";

/* Reassign value */
document.cookie = "name=queness; expires=Fri, 11-Sep-2010 23:59:59 GMT; path=/";

/* Erase a cookie, put a past date */
document.cookie = "name=queness; expires=Fri, 08-Sep-2009 23:59:59 GMT; path=/";

Cookie Functions to Make Your Life Easier

Kudos to Quirksmode.org, they have created these functions to create, read and erase cookie easily. We don't even have to remember the GMT date format, we just have to set number of days and it will do the rest for us. Pretty good huh?

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

A Simple Implementation Menu

Alright, a really simple real implementation, it remembers which menu item you have just clicked, and the script assign a selected class to it. It highlights the current menu item.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" 
	"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title>untitled</title>
	<script type="text/javascript" src="/javascript/article/Cookie_and_Javascript_How_to_Handle.php/js/jquery-1.3.1.min.js"></script>
	<link type="text/css" rel="stylesheet" href="/javascript/article/Cookie_and_Javascript_How_to_Handle.php/"/>
	<script>
	
	$(document).ready(function () {

		//for debugging purpose, so that you can see what is in the menu cookie
		$('#debug').html('Cookie Content : ' + readCookie('menu'));

		//if cookie menu exists
		if (readCookie('menu')) {
			
			//loop through the menu item
			$('#menu a').each(function () {
				//match the correct link and add selected class to it
				if ($(this).html() == readCookie('menu')) $(this).addClass('selected');
			});	
		}

		$('#menu a').click(function () {

			//Set the cookie according to the text in the link
			createCookie('menu', $(this).html(),1);
		});
		
	});


	/* Cookie Function */
	function createCookie(name, value, days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
	}

	function readCookie(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	}

	function eraseCookie(name) {
		createCookie(name,"",-1);
	}

	</script>
	
	<style>
	ul {
		padding:0;
		margin:0;
		list-style:none;
	}
	
		li {
			float:left;
			margin:0 10px;

		}
		
		li a {
			border-bottom:3px solid #ccc;	
			text-decoration:none;
			display:block;
			color:#666;
		}
		
		li a:hover {
			border-bottom:3px solid #000;					
		}
		
		li a.selected {
			border-bottom:3px solid #000;					
		}
		
	.clear {
		clear:both;	
	}
	</style>
</head>
<body>

<ul id="menu">
<li><a href="/javascript/article/Cookie_and_Javascript_How_to_Handle.php/index.html">Home</a></li>
<li><a href="/javascript/article/Cookie_and_Javascript_How_to_Handle.php/index.html">Tips</a></li>
<li><a href="/javascript/article/Cookie_and_Javascript_How_to_Handle.php/index.html">Porfolios</a></li>
<li><a href="/javascript/article/Cookie_and_Javascript_How_to_Handle.php/index.html">About</a></li>
<li><a href="/javascript/article/Cookie_and_Javascript_How_to_Handle.php/index.html">Contact</a></li>
</ul>

<div class="clear"></div>

<br/><br/>
<div id="debug"></div>

</body>
</html>
iPhoneKer.com
Save up to 630$ when buy new iPhone 15

GateIO.gomymobi.com
Free Airdrops to Claim, Share Up to $150,000 per Project

https://tooly.win
Open tool hub for free to use by any one for every one with hundreds of tools

chatGPTaz.com, chatGPT4.win, chatGPT2.fun, re-chatGPT.com
Talk to ChatGPT by your mother language

Dall-E-OpenAI.com
Generate creative images automatically with AI

AIVideo-App.com
Render creative video automatically with AI

JavaScript theo ngày


Google Safe Browsing McAfee SiteAdvisor Norton SafeWeb Dr.Web