http://msdn.microsoft.com/en-us/library/ms531424(v=vs.85).aspx

에서 참조

userData Behavior

30 out of 50 rated this helpful Rate this topic

Enables the object to persist data in user data.

Syntax

XML<Prefix: CustomTag ID=sID STYLE="behavior:url('#default#userData')" /> HTML <ELEMENT STYLE="behavior:url('#default#userData')" ID=sID> Scripting object .style.behavior = "url('#default#userData')" object .addBehavior ("#default#userData")

Possible Values

Prefix Prefix that associates the CustomTag with an XML namespace. This prefix is set using the XMLNS attribute of the HTML tag. CustomTag User-defined tag. sIDString that specifies a unique identifier for the object.

Members Table

The following table lists the members exposed by the userData object.

Attributes/Properties
PropertyDescriptionexpires Sets or retrieves the expiration date of data persisted with the userData behavior. XMLDocumentRetrieves a reference to the XML
Methods
MethodDescriptiongetAttribute Retrieves the value of the specified attribute. load Loads an object participating in userData persistence from a UserData store. removeAttribute Removes the specified attribute from the object. save Saves an object participating in userData persistence to a UserData store. setAttributeSets the value of the specified attribute.

Remarks

security note Security Alert  For security reasons, a UserData store is available only in the same directory and with the same protocol used to persist the store.
security note Security Alert  Using this behavior incorrectly can compromise the security of your application. Data in a UserData store is not encrypted and therefore not secure. Any application that has access to the drive where UserData is saved has access to the data. Therefore, it is recommended that you not persist sensitive data like credit card numbers. For more information, see Security Considerations: DHTML and Default Behaviors.

The userData behavior persists information across sessions by writing to a UserData store. This provides a data structure that is more dynamic and has a greater capacity than cookies. The capacity of the UserData store depends on the security zone of the domain. The following table shows the maximum amount of UserData storage that is available for an individual document and also the total available for an entire domain, based on the security zone.

Security ZoneDocument Limit (KB)Domain Limit (KB)Local Machine1281024Intranet51210240Trusted Sites1281024Internet1281024Restricted64640

See URLACTION_HTML_USERDATA_SAVE for information on how the userData behavior is regulated. See About URL Security Zones Templates for further information on the default URL policy settings for each of the five security zone templates.

The userData behavior persists data across sessions, using one UserData store for each object. The UserData store is persisted in the cache using the save and load methods. Once the UserData store has been saved, it can be reloaded even if Windows Internet Explorer has been closed and reopened.

Setting the userData behavior class on the html, head, title, or style object causes an error when the save or load method is called.

The required style can be set inline or in the document header, as follows:

Copy
   <STYLE>

      .storeuserData {behavior:url(#default#userData);}

   </STYLE>

An ID is optional for userData, but including one improves performance.

The userData behavior is available as of Microsoft Internet Explorer 5, in the Microsoft Win32 and Unix platforms.

Examples

This example uses the userData behavior to preserve information in a UserData Store.

Copy
<html>



<head>

<style type="text/css">

.storeuserData {

    behavior: url(#default#userData);

}

</style>



function fnSaveInput(){

   var oPersist=oPersistForm.oPersistInput;

   oPersist.setAttribute("sPersist",oPersist.value);

   oPersist.save("oXMLBranch");

}

function fnLoadInput(){

   var oPersist=oPersistForm.oPersistInput;

   oPersist.load("oXMLBranch");

   oPersist.value=oPersist.getAttribute("sPersist");

}



</head>



<body>



<form id="oPersistForm">

    <input class="storeuserData" type="text" id="oPersistInput">

    <input type="button" value="Load" onclick="fnLoadInput()">

    <input type="button" value="Save" onclick="fnSaveInput()">

</form>



</body>



</html>

Code example: http://samples.msdn.microsoft.com/workshop/samples/author/persistence/userData_1.htm

The following example uses the userData behavior in a custom tag to preserve information in a UserData Store.

Copy
<html xmlns:sdk="">



<head>

<style type="text/css">

sdk:cacher {

    behavior: url(#default#userData);

}

</style>



function fnSaveInput(){

   cachetag.setAttribute("sPersist",txt1.value);

   cachetag.save("cache");

}

function fnLoadInput(){

   cachetag.load("cache");

   cachetag.value=cachetag.getAttribute("sPersist");

}



</head>



<body>



<sdk:cacher id="cachetag"></sdk:cacher>

<input type="button" value="Load" onclick="fnLoadInput()">

<input type="button" value="Save" onclick="fnSaveInput()">

<input type="text" id="txt1" value="some value">



</body>



</html>

Introduction to Persistence

13 out of 27 rated this helpful Rate this topic

Note  As of December 2011, this topic has been archived and is no longer actively maintained. For more information, see Archived Content. For information, recommendations, and guidance regarding the current version of Windows Internet Explorer, see Internet Explorer Developer Center.

Persistence enables authors to specify an object to persist on the client during the current and later sessions using Dynamic HTML (DHTML) behaviors. Persistence allows Microsoft Internet Explorer 5 and later to retain Web page information, styles, variables, and state. For example, a collapsible list of links within a table of contents can remain expanded to the user’s choice upon leaving and later returning to the page. Or, a search engine query form can retain the last-used search string.

Persistence is implemented as a behavior. The new persistence behaviors include:

  • saveFavorite—persists page state and information when the web page is saved as a favorite.
  • saveHistory—persists page state and information within the current session’s memory.
  • saveSnapshot—persists page state and information directly in the page when users save the Web page to their hard disk.
  • userData—persists page state and information within an XML store, a hierarchical data structure.

Persistence creates new opportunities for the author. Information that persists beyond a single page without support from the server, or within the finite scope of cookies, can increase the speed of navigation and content authoring.

These behaviors can be used to preserve information in the browser’s history, in favorites, in an XML store, or directly within a Web page saved to disk. When a user returns to a persisted page, the state of the page can be restored. By allowing information to safely reside on the client, fewer server transactions are required. Custom start pages and Web applications prosper because information can continue to exist without the paternal support of the server, or repeated server queries. A Web page can remain interactive to a degree, after the connection with the host has been severed, by persisting required information on the client.

Benefits

Use of persistence in Internet Explorer 5 breaks away from the tradition of using cookies and session files to store information. The Microsoft model for client/server relationships using persistence and Internet Explorer 5 is pragmatic; it maintains the same-domain security policy associated with cookies while increasing storage and management capabilities.

Server solutions Persistence solutions Start pages Custom start pages often rely on cookies and server-side databases to preserve client-specific information. Storing information such as client capabilities, favorite styles, and favorite content requires additional queries to the server to retrieve the information. This results in increased download time for the client and increased processing demands on the server.Persistence via Dynamic HTML (DHTML) behaviors allows a page author to store information on the client. This reduces the need to query a server database for client-specific information and increases the overall performance of the page. Persistence stores the data hierarchically, making it more accessible.Web appsWeb-based applications have remained tied to the server for the back-end strength and processing power they require. A Web site that includes a basic form to be sent in e-mail uses a server to handle the request, or a script to process any e-mail beyond a conventional note.A persistent Web page can be saved with its form values intact, making it easier to transfer or preserve an entire document. Persistence introduces a new paradigm for Web applications by giving authors the ability to produce complex Web-based applications that take advantage of the client’s processing power.FormsAdvanced search engines and information entry and retrieval forms often rely on session variables and files to preserve information across Web pages. The server must send and store the same information with each new visit to the Web page, taxing the Web server and the Internet line.While there is some information that should remain on the server, the rest can be stored on the client. Client-side scripting within each Web page can perform the necessary validation routines, leaving the server to higher-level security concerns. Since persisted information maintains a similar same-domain security structure as cookies, the client can be assured that rogue Web sites will not glean such information from their computers.

Using Persistence

Persistence behaviors require certain conditions before they can be used. A meta tag directs the browser that the page is persistent. Persistent elements are identified with a CLASS and an ID property. The onsave and onload event handlers can be defined for nondefault handling.

Behavior Description saveFavoritePersists an object across sessions when the page has been saved as a favorite.

The getAttribute and setAttribute methods are used to store information on a persistent object. The onload and onsave event handlers can be used to call the methods.

The saveFavorite behavior is ideal for persisting user-selected styles within a favorite or shortcut. The persisted information is stored within each favorite, allowing multiple favorites with different persisted information to exist.

saveHistoryPersists an object during the current session.

The getAttribute and setAttribute methods can be used to store information on objects participating in persistence. The onload and onsave event handlers can be used to call the methods.

The saveHistory behavior is ideal for storing information only while the browser is open, such as page state for collapsible content, or dynamic styles.

saveSnapshotPersists an object across sessions when a page has been saved as Web Page, HTML Only.

Form elements persist automatically. Script blocks designated to persist can contain only variables. Script objects and comments are removed. Qualifying variables from external sources on persisting script blocks are inserted.

The saveSnapshot behavior is ideal for persisting Web application information to the client’s disk for later retrieval.

userDataPersists an object across sessions in a UserData store (an arbitrary storage facility) when the object has been explicitly saved.

Form elements, styles, and dynamic values can be persisted using the getAttribute and setAttribute methods, and then explicitly saved using the load and save methods.

The userData behavior is ideal for persisting information across sessions and storing information in a hierarchical structure. It provides a good alternative to using cookies. The capacity of the userData store is 64 KB per page, with a limit of 640 KB per domain, for restricted sites. For security reasons, a userData store is available only in the same directory and with the same protocol used to persist the store.

Security Warning:  Using these behavior incorrectly can compromise the security of your application. The saveFavorite, saveSnapshot, and userData behaviors persist data as plain text in a saved Web page. Text is not encrypted and therefore not secure. Any application that has access to the drive where the page is saved also has access to the data and can tamper with it. Therefore, it is recommended that you not persist sensitive data like credit card numbers. For more information, see Security Considerations: DHTML and Default Behaviors.

An ID is not required for the saveFavorite and saveHistory behaviors, but is recommended for performance. The style element also can be set inline on a persistent object.

Example Uses of Persistence

The following examples show how to use behaviors to implement persistence.

The following examples shows the saveFavorite behavior.

<!-- Tell the browser the page is persistent-->
<META NAME="save" CONTENT="favorite">
<!-- Define the class for the persistent object-->
<STYLE>
    .saveFavorite {behavior:url(#default#savefavorite);}
</STYLE>

// Record information to the persistent object as an attribute.
function fnSave(){
   oPersistInput.setAttribute("sPersistAttr",oPersistInput.value);
}
// Retrieve information from a persistent object.
function fnLoad(){
   oPersistInput.value=oPersistInput.getAttribute("sPersistAttr");
}

:
<!-- The CLASS enables the object to persist, the event handlers 
     fire the scripted functions.-->
<INPUT
   TYPE="text"
   CLASS="saveFavorite"
   ID="oPersistInput"
   onload="fnLoad()"
   onsave="fnSave()"
>

Click to view sample.

The following example shows the saveHistory behavior.

<!-- Tell the browser the page is persistent-->
<META NAME="save" CONTENT="history">
<!-- Define the class for the persistent object-->
<STYLE>
    .saveHistory {behavior:url(#default#savehistory);}
</STYLE>
:
<!-- The default behavior is to persist form elements.
   When the saveHistory behavior is defined, form elements
   will not persist unless they have a class.
-->
This persists:
<INPUT TYPE="text" CLASS="saveHistory" ID="oPersistInput">
This does not persist:
<INPUT TYPE="text">

Click to view sample.

The following example shows the saveSnapshot behavior.

<!-- Tell the browser the page is persistent-->
<META NAME="save" CONTENT="snapshot">
<!-- Define the class for the persistent object-->
<STYLE>
    .saveSnapshot {behavior:url(#default#savesnapshot);}
</STYLE>
:
<!-- When the page is saved, the information entered in the
     persistent form element will be inserted as the value
     within the HTML file.-->
<INPUT TYPE=text CLASS=saveSnapshot ID=oPersistInput>
:

Click to view sample.

The following example shows the userData behavior.

<!-- Define the class for the persistent object-->
<STYLE>
    .userData {behavior:url(#default#userdata);}
</STYLE>

    function fnSaveInput(){
   
// Persistent information is stored as an attribute
// on the persistent object, and saved within a
// UserData store.
      var oPersist=oPersistForm.oPersistInput;
      oPersist.setAttribute("sPersist",oPersist.value);
      oPersist.save("oXMLBranch");
	  
   }
    function fnLoadInput(){

// Persistent information is loaded from a UserData store
// and the value is restored from the persisted attribute.

      var oPersist=oPersistForm.oPersistInput;
      oPersist.load("oXMLBranch");
      oPersistInput.value=oPersistInput.getAttribute("sPersist");
   }

:
<FORM ID="oPersistForm">
<INPUT class=userData type=text id=oPersistInput>
<INPUT type=button value="Load" onclick="fnLoadInput()">
<INPUT type=button value="Save" onclick="fnSaveInput()">
</FORM>

Click to view sample.

Persisting Content in XML

The XMLDocument property allows the saveFavorite, saveHistory, and userData behaviors to access the XML Document Object Model (DOM). Using the XML DOM, persistent objects have access to the objects, properties, and methods that allow the author to build hierarchical data structures.

var oXMLDocument=oPersistText.XMLDocument;
var oNode=oXMLDocument.createNode("element","MyElement", "");
oNode.nodeValue="The value of MyElement";
oXMLDocument.documentNode.insertNode("MyElement");

In XML, this would yield:

<MyElement>The value of MyElement</MyElement>

Persistence How-Tos

Persistence introduces a broad expanse of possibilities. The following how-to articles cover some of the more interesting, albeit easy-to-employ, uses of persistence.

Related topics

Dynamic HTML (DHTML) Articles Introduction to DHTML Behaviors Client Capabilities Default Behaviors Reference

Send comments about this topic to Microsoft

Build date: 10/26/2012

http://msdn.microsoft.com/en-us/library/ms531421(v=vs.85).aspx

에서 참조

 

saveFavorite Behavior

1 out of 6 rated this helpful Rate this topic

Enables the object to persist data in a favorite Web site.

Syntax

XML<Prefix: CustomTag ID=sID STYLE="behavior:url('#default#saveFavorite')" /> HTML <ELEMENT STYLE="behavior:url('#default#saveFavorite')" ID=sID> Scripting object .style.behavior = "url('#default#saveFavorite')" object .addBehavior ("#default#saveFavorite")

Possible Values

Prefix Prefix that associates the CustomTag with an XML namespace. This prefix is set using the XMLNS attribute of the HTML tag. CustomTag User-defined tag. sIDString that specifies a unique identifier for the object.

Members Table

The following table lists the members exposed by the saveFavorite object.

Attributes/Properties
PropertyDescriptionXMLDocumentRetrieves a reference to the XML
Events
EventDescriptiononload Fires from a persistent element when the page reloads. onsaveFires from a persisted element when the Web page is saved or bookmarked, or when the user navigates away from the page.
Methods
MethodDescriptiongetAttribute Retrieves the value of the specified attribute. removeAttribute Removes the specified attribute from the object. setAttributeSets the value of the specified attribute.

Remarks

The saveFavorite behavior allows the current state of a page to be saved when the user adds the page to the Favorites menu. When the user returns to the page through a shortcut or the Favorites menu, the state of the page is restored.

The saveFavorite behavior persists data across sessions, using one userData store for each object. If two objects try to use the same attribute, both are persisted in the userData store for each element. The saveFavoriteuserData store is persisted in the Favorites .ini file, which includes the URL of the page as well as the userData store. When the page is loaded through a shortcut or the Favorites menu, the data from the userData store is loaded from the .ini file, even if the user closes and reopens Windows Internet Explorer.

For example, a page with several dynamically updated styles can save these updates using the onload and onsave events. The style values can be saved as attributes when onsave fires, and restored when onload fires.

security note Security Alert  Using this behavior incorrectly can compromise the security of your application. This behavior uses a userData store, which is not encrypted and therefore not secure. Any application that has access to the drive where userData is saved has access to the data. Therefore, it is recommended that you not persist sensitive data like credit card numbers. For more information, see Security Considerations: DHTML and Default Behaviors.

To persist the state of a page by adding it to the browser Favorites menu, first define a Cascading Style Sheets (CSS) style that applies the saveFavorite behavior. Then use this style in the tags containing content that needs to be persisted. The required style can be set inline or in the document header, as follows:

Copy
   <STYLE>

      .sFavorite {behavior:url(#default#savefavorite);}

   </STYLE>

An ID is optional for saveFavorite, but including one improves performance.

The saveFavorite behavior is available as of Microsoft Internet Explorer 5, in the Microsoft Win32 and Unix platforms.

Example

This example uses the saveFavorite behavior to persist information after the user saves the page as a favorite.

Copy
<HTML>

<HEAD>

<STYLE>

   .sFavorite {behavior:url(#default#savefavorite);}

</STYLE>



   function fnSaveInput(){

      oPersistInput.setAttribute("sPersistValue",oPersistInput.value);

   }

   function fnLoadInput(){

      oPersistInput.value=oPersistInput.getAttribute("sPersistValue");

   }



</HEAD>

<BODY>

<INPUT class=sFavorite onsave="fnSaveInput()" onload="fnLoadInput()" type=text id=oPersistInput>

</BODY>

</HTML>

http://www.quirksmode.org/js/cookies.html

에서 참조

 

Cookies

Cookies were originally invented by Netscape to give ‘memory’ to web servers and browsers. The HTTP protocol, which arranges for the transfer of web pages to your browser and browser requests for pages to servers, is state-less, which means that once the server has sent a page to a browser requesting it, it doesn’t remember a thing about it. So if you come to the same web page a second, third, hundredth or millionth time, the server once again considers it the very first time you ever came there.

This can be annoying in a number of ways. The server cannot remember if you identified yourself when you want to access protected pages, it cannot remember your user preferences, it cannot remember anything. As soon as personalization was invented, this became a major problem.

Cookies were invented to solve this problem. There are other ways to solve it, but cookies are easy to maintain and very versatile.

How cookies work

A cookie is nothing but a small text file that’s stored in your browser. It contains some data:

  1. A name-value pair containing the actual data
  2. An expiry date after which it is no longer valid
  3. The domain and path of the server it should be sent to

As soon as you request a page from a server to which a cookie should be sent, the cookie is added to the HTTP header. Server side programs can then read out the information and decide that you have the right to view the page you requested or that you want your links to be yellow on a green background.

So every time you visit the site the cookie comes from, information about you is available. This is very nice sometimes, at other times it may somewhat endanger your privacy. Fortunately more and more browsers give you the opportunity to manage your cookies (deleting the one from the big ad site, for example).

Cookies can be read by JavaScript too. They’re mostly used for storing user preferences.

name-value

Each cookie has a name-value pair that contains the actual information. The name of the cookie is for your benefit, you will search for this name when reading out the cookie information.

If you want to read out the cookie you search for the name and see what value is attached to it. Read out this value. Of course you yourself have to decide which value(s) the cookie can have and to write the scripts to deal with these value(s).

Expiry date

Each cookie has an expiry date after which it is trashed. If you don’t specify the expiry date the cookie is trashed when you close the browser. This expiry date should be in UTC (Greenwich) time.

Domain and path

Each cookie also has a domain and a path. The domain tells the browser to which domain the cookie should be sent. If you don’t specify it, it becomes the domain of the page that sets the cookie, in the case of this page www.quirksmode.org.
Please note that the purpose of the domain is to allow cookies to cross sub-domains. My cookie will not be read by search.quirksmode.org because its domain is www.quirksmode.org . When I set the domain to quirksmode.org, the search sub-domain may also read the cookie.
I cannot set the cookie domain to a domain I’m not in, I cannot make the domain www.microsoft.com . Only quirksmode.org is allowed, in this case.

The path gives you the chance to specify a directory where the cookie is active. So if you want the cookie to be only sent to pages in the directory cgi-bin, set the path to /cgi-bin. Usually the path is set to /, which means the cookie is valid throughout the entire domain.
This script does so, so the cookies you can set on this page will be sent to any page in the www.quirksmode.org domain (though only this page has a script that searches for the cookies and does something with them).

document.cookie

Cookies can be created, read and erased by JavaScript. They are accessible through the property document.cookie. Though you can treat document.cookie as if it’s a string, it isn’t really, and you have only access to the name-value pairs.

If I want to set a cookie for this domain with a name-value pair ‘ppkcookie1=testcookie’ that expires in seven days from the moment I write this sentence, I do

document.cookie =

  'ppkcookie1=testcookie; expires=Thu, 2 Aug 2001 20:47:11 UTC; path=/'

  1. First the name-value pair (’ppkcookie1=testcookie’)
  2. then a semicolon and a space
  3. then the expiry date in the correct format (’expires=Thu, 2 Aug 2001 20:47:11 UTC’)
  4. again a semicolon and a space
  5. then the path (path=/)

This is a very strict syntax, don’t change it! (Of course the script manages these dirty bits for you)

Also, even though it looks like I’m writing this whole string to the string document.cookie, as soon as I read it out again I only see the name-value pair:

ppkcookie1=testcookie

If I want to set another cookie, I again do

document.cookie =

  'ppkcookie2=another test; expires=Fri, 3 Aug 2001 20:47:11 UTC; path=/'

The first cookie is not overwritten, as it would when document.cookie would be a real string. Instead the second one is added to document.cookie, so if we read it out we get

ppkcookie1=testcookie; ppkcookie2=another test

If I reset a cookie

document.cookie =

  'ppkcookie2=yet another test; expires=Fri, 3 Aug 2001 20:47:11 UTC; path=/'

the old cookie is overwritten and document.cookie reads

ppkcookie1=testcookie; ppkcookie2=yet another test

To read out a cookie you have to treat document.cookie as a string and search for certain characters (semicolons, for instance) and for the cookie name. I’ll explain how to do it below.

Finally, to remove a cookie, set it with an expiry date before today. The browser sees that the cookie has expired and removes it.

document.cookie =

  'ppkcookie2=yet another test; expires=Fri, 27 Jul 2001 02:47:11 UTC; path=/'

Example

If you’re thoroughly confused by all this strange syntax, try the example below. You can set two cookies, ppkcookie1 and ppkcookie2. Fill in the desired value in the text box.

The value of the cookie should be

Create cookie 1
Read cookie 1
Erase cookie 1.

Create cookie 2
Read cookie 2
Erase cookie 2.

For comparision, read out document.cookie.

I set the cookies to remain active for seven days. If you return to this page within that time, you’ll get an alert that the cookie(s) is/are still active. Try it by setting a cookie, then reloading this page.

The scripts

These are the three scripts you need.

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);

}

Explanation

The functions are not very difficult, the hardest part is creating the correct syntax for setting a cookie.

createCookie

When calling createCookie() you have to give it three bits of information: the name and value of the cookie and the number of days it is to remain active. In this case the name-value pair should become ppkcookie=testcookie and it should be active for 7 days.

createCookie('ppkcookie','testcookie',7)

If you set the number of days to 0 the cookie is trashed when the user closes the browser. If you set the days to a negative number the cookie is trashed immediately.

The function receives the arguments and starts doing its job.

function createCookie(name,value,days) {

First of all see if there is a days value. If there isn’t we don’t need to do the time calculation.

	if (days) {

If there is, create a new Date object containing the current date.

		var date = new Date();

Now get the current Time (in milliseconds) and add the required number of days (in milliseconds). Set the Time of the date to this new value, so that it now contains the date in milliseconds that the cookie should expire.

		date.setTime(date.getTime()+(days*24*60*60*1000));

Set the variable expires to this date in the UTC/GMT format required by cookies.

		var expires = "; expires="+date.toGMTString();

	}

If 0 is passed to the function, expires is not set and the cookie expires when the user closes his browser..

	else var expires = "";

Finally write the new cookie into document.cookie in the correct syntax.

	document.cookie = name+"="+value+expires+"; path=/";

}

Cookie created.

readCookie

To read out a cookie, call this function and pass the name of the cookie. Put the name in a variable. First check if this variable has a value (if the cookie does not exist the variable becomes null, which might upset the rest of your function), then do whatever is necessary.

var x = readCookie('ppkcookie1')

if (x) {

	[do something with x]

}

The function receives the argument and starts.

function readCookie(name) {

We’re going to search for the name of the cookie, followed by an =. So create this new string and put it in nameEQ:

	var nameEQ = name + "=";

Then split document.cookie on semicolons. ca becomes an array containing all cookies that are set for this domain and path.

	var ca = document.cookie.split(';');

Then we go through the array (so through all cookies):

	for(var i=0;i < ca.length;i++) {

Set c to the cookie to be checked.

		var c = ca[i];

If the first character is a space, remove it by using the substring() method. Continue doing this until the first character is not a space.

		while (c.charAt(0)==' ') c = c.substring(1,c.length);

Now string c begins with the name of the current cookie. If this is the name of the desired cookie

		if (c.indexOf(nameEQ) == 0)

we’ve found what we were looking for. We now only need to return the value of the cookie, which is the part of c that comes after nameEQ. By returning this value we also end the function: mission accomplished.

		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);

	}

If, after having gone through all cookies, we haven’t found the name we’re looking for, the cookie is not present. We return null.

	return null;

}

Cookie read.

eraseCookie

Erasing is extremely simple.

eraseCookie('ppkcookie')

Pass the name of the cookie to be erased

function eraseCookie(name) {

and call createCookie() to set the cookie with an expiry date of one day ago.

	createCookie(name,"",-1);

}

The browser, seeing that the expiry date has passed, immediately removes the cookie.

http://www.w3schools.com/js/js_cookies.asp

에서 참조

 

What is a Cookie?

A cookie is a variable that is stored on the visitor’s computer. Each time the same computer requests a page with a browser, it will send the cookie too. With JavaScript, you can both create and retrieve cookie values.

Examples of cookies:

  • Name cookie – The first time a visitor arrives to your web page, he or she must fill in her/his name. The name is then stored in a cookie. Next time the visitor arrives at your page, he or she could get a welcome message like “Welcome John Doe!” The name is retrieved from the stored cookie
  • Date cookie – The first time a visitor arrives to your web page, the current date is stored in a cookie. Next time the visitor arrives at your page, he or she could get a message like “Your last visit was on Tuesday August 11, 2005!” The date is retrieved from the stored cookie

Create and Store a Cookie

In this example we will create a cookie that stores the name of a visitor. The first time a visitor arrives to the web page, he or she will be asked to  fill in her/his name. The name is then stored in a cookie. The next time the visitor arrives at the same page, he or she will get welcome message.

First, we create a function that stores the name of the visitor in a cookie variable:

function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? “” : “; expires=”+exdate.toUTCString());
document.cookie=c_name + “=” + c_value;
}

The parameters of the function above hold the name of the cookie, the value of the cookie, and the number of days until the cookie expires.

In the function above we first convert the number of days to a valid date, then we add the number of days until the cookie should expire. After that we store the cookie name, cookie value and the expiration date in the document.cookie object.

Then, we create another function that returns a specified cookie:

function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(“;”);
for (i=0;i<ARRcookies.length;i++)
{
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf(“=”));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf(“=”)+1);
  x=x.replace(/^s+|s+$/g,“”);
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}

The function above makes an array to retrieve cookie names and values, then it checks if the specified cookie exists, and returns the cookie value.

Last, we create the function that displays a welcome message if the cookie is set, and if the cookie is not set it will display a prompt box, asking for the name of the user, and stores the username cookie for 365 days, by calling the setCookie function:

function checkCookie()
{
var username=getCookie(“username”);
  if (username!=null && username!=“”)
  {
  alert(“Welcome again ” + username);
  }
else
  {
  username=prompt(“Please enter your name:”,“”);
  if (username!=null && username!=“”)
    {
    setCookie(“username”,username,365);
    }
  }
}

All together now:

Example

<!DOCTYPE html>
<html>
<head>

function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(“;”);
for (i=0;i  {
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf(“=”));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf(“=”)+1);
  x=x.replace(/^s+|s+$/g,“”);
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}

function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? “” : “; expires=”+exdate.toUTCString());
document.cookie=c_name + “=” + c_value;
}

function checkCookie()
{
var username=getCookie(“username”);
if (username!=null && username!=“”)
  {
  alert(“Welcome again ” + username);
  }
else
  {
  username=prompt(“Please enter your name:”,“”);
  if (username!=null && username!=“”)
    {
    setCookie(“username”,username,365);
    }
  }
}

</head>
<body onload=“checkCookie()”>
</body>
</html>

Try it yourself »

The example above runs the checkCookie() function when the page loads.

http://www.thesitewizard.com/javascripts/cookies.shtml

에서 참조

How to Use Cookies in JavaScript

by Christopher Heng, thesitewizard.com

Cookies are bits of data that a browser stores in your visitor’s computer. They are useful in that they allow you to store things like your visitor’s preferences when they visit your site, or other types of data specific to a particular user. This tutorial deals with how you can use JavaScript to create, store, retrieve and delete cookies.

What Kinds of Data Can Be Stored in a Cookie?

A cookie is basically a string of text characters not longer than 4 KB. Cookies are set in name=value pairs, separated by semi-colons. For example, a cookie might be a string like the following:

“theme=blue; max-age=60; path=/; domain=thesitewizard.com”

This example cookie has 4 variable/value pairs:

  • max-age, which is set to 60,
  • path, which is set to the slash character “/”,
  • domain, which is set to “thesitewizard.com”,
  • and theme, which is set to “blue”.

The variables “max-age”, “path” and “domain” are special variable names that are recognized by the browser to control things like the lifespan of the cookie and the URLs for which the cookie is valid. Only the “theme” variable in my example contains the real data that I wish to set. You can create any variable name you want, and set it to whatever value you wish, subject to the following constraints:

  • max-age

    Cookies have, by default, a lifespan of the current browser session. As soon as your visitor closes his browser, your cookie disappears. To make it last longer, you will need to set the max-age variable to contain the number of seconds (yes, seconds) you want the cookie to last.

    For example, if you want your cookie to last 30 days, set it to 2,592,000. Actually instead of pre-calculating this and putting it into your script, you can have the JavaScript interpreter calculate it for you at run time, and simply encode it as

    “theme=blue; max-age=” + 60*60*24*30 + “; path=/; domain=thesitewizard.com”

    This is superior to writing a huge number that you’ll forget the meaning of in the future.

  • path

    By default cookies are valid only for web pages in the directory of the current web page that stored them, as well as its descendants. That is, if a cookie is set by http://example.com/abc/webpage.html, it will be valid for http://example.com/abc/yet-another-page.html as well as http://example.com/abc/Sub-Folder/index.html, but not for http://example.com/index.html.

    If you want the cookie to be valid in some other directory, say, http://example.com/special/, you will need to set the path variable to contain the value “/special”. If you want the cookie to be valid everywhere on your site, set it to the root of your web directory, that is, “/”.

  • domain

    Another special variable name that you may want to take note of is the domain variable. Cookies set in sub-domains like www.example.com will only be valid for that subdomain. If you want it to be valid for all sub-domains of example.com, you will need to set the domain to point to “example.com”. The cookie will then be valid for “www.example.com”, “blog.example.com”, and whatever other subdomains that you may have.

    Note that for security reasons, if your domain is example.com, browsers will not accept a cookie for a different domain, like google.com.

  • secure

    There’s another variable that has special meaning: secure. This variable should not be assigned any value. Including it means that the cookie will only be sent if your visitor is visiting your website over a secure connection.

  • expires

    The expires variable is obsolete although still supported by today’s browsers. Use the max-age variable instead, since it is easier to use. Be careful not to use “expires” as a variable name to store your data as well.

  • No spaces, commas, semi-colons

    Your cookie values cannot have any embedded whitespaces, commas or semi-colons. If you have any, they must be converted to its “encoded” equivalent. The easiest way to do this is to use the encodeURIComponent() function to encode it, and the decodeURIComponent() function to decode it when you read the cookie.

    Expanding on my earlier example, if you want to set a “theme” variable to “blue theme”, you can do it this way:

    “theme=” + encodeURIComponent(“blue theme”) + “; max-age=” + 60*60*24*30 + “; path=/; domain=thesitewizard.com”

    Of course in the above case, since there is only one space character to encode, you can do it manually as “blue%20theme” as well.

  • Cookie Limits

    Although different browsers may implement different limits for cookies, the bare minimum that they are supposed to support is as follows:

    • Cookie length: 4 KB. The total length of your string, including all the variables with special meaning, should not be more than 4,096 characters.

    • Maximum number of cookies per web server: 20.

    • Total number of cookies supported by the browser: 300. This includes cookies stored by other websites.

How to Set a Cookie

Setting a cookie is extremely simple. Just assign the string you want for the cookie to the document.cookie property. For example, if I want to set the cookie given in my example above, I can simply include the following JavaScript code.

document.cookie =

    "theme=" + encodeURIComponent("blue theme") +

    "; max-age=" + 60*60*24*30 +

    "; path=/; domain=thesitewizard.com" ;

To make your life easier, you may want to include the following function in the HEAD section of your web page, and then use it to set your cookies.

(Note: If you are using IE 6, you may have difficulty cutting/copying the code. See my other article for the solution.)

function set_cookie ( cookie_name, cookie_value,

    lifespan_in_days, valid_domain )

{

    // http://www.thesitewizard.com/javascripts/cookies.shtml

    var domain_string = valid_domain ?

                       ("; domain=" + valid_domain) : '' ;

    document.cookie = cookie_name +

                       "=" + encodeURIComponent( cookie_value ) +

                       "; max-age=" + 60 * 60 *

                       24 * lifespan_in_days +

                       "; path=/" + domain_string ;

}

To set a cookie with the name “colourscheme” and the value “Shades of Purple” that will last 7 days for all URLs in the domain example.com, call the function this way:

set_cookie( "colourscheme", "Shades of Purple", 7, "example.com" );

The function saves you from the tedium of remembering all the details needed to set a cookie. It uses the defaults that most webmasters want, like making the cookie valid for all paths in the domain, and setting the cookie in terms of days (instead of seconds). In addition, if you only want to set the cookie for your current domain, you can call it without the third parameter:

set_cookie( "colourscheme", "Shades of Purple", 7 );

How to Read a Cookie

Setting a cookie is great and all that, but a cookie is only useful if one can actually read what one has set previously.

To read a cookie, just read the string currently held in document.cookie. Since the string includes all the usual overhead for a cookie, like “max-age”, “path” and “domain”, you will need to parse the string to obtain the value you want. There are many ways to do this, such as splitting the string into separate tokens, using one of the substring search functions, or using regular expressions.

The following function allow you to easily get the cookie value you want by simply specifying the variable name.

function get_cookie ( cookie_name )

{

    // http://www.thesitewizard.com/javascripts/cookies.shtml

    var cookie_string = document.cookie ;

    if (cookie_string.length != 0) {

        var cookie_value = cookie_string.match (

                        '(^|;)[s]*' +

                        cookie_name +

                        '=([^;]*)' );

        return decodeURIComponent ( cookie_value[2] ) ;

    }

    return '' ;

}

To use the function, include it somewhere in the HEAD of your web page, and call it with the name of the cookie variable that you set earlier. The string returned will be the decoded string you used to set the cookie with set_cookie(). The function does the hard work of searching for the string, separating the value out, and decoding it.

For example, to retrieve the “colourscheme” cookie set earlier, do the following:

colourscheme = get_cookie( "colourscheme" );

If get_cookie() cannot find the cookie, it will return an empty string. This may happen even if you have set a cookie, since the visitor may have deleted it, or alternatively, disabled cookie support in his/her browser.

How to Delete a Cookie

There are times when you may want to delete a cookie, such as when a visitor logs out of your site. To do this, set the max-age variable to 0 (zero) for the same cookie in the same path and domain. You can use the following function to do this:

function delete_cookie ( cookie_name, valid_domain )

{

    // http://www.thesitewizard.com/javascripts/cookies.shtml

    var domain_string = valid_domain ?

                       ("; domain=" + valid_domain) : '' ;

    document.cookie = cookie_name +

                       "=; max-age=0; path=/" + domain_string ;

}

For example, to delete the cookie set in the example above, do this:

delete_cookie( "colourscheme", "example.com" );

Note that this function assumes that you have set the cookie using my set_cookie() function, which always sets the path as “/”. If you used your own cookie setting code that does not set the path to the root of your website, you should write your own cookie deletion code that specifies the same path you set.

Furthermore, if you did not set a domain name when calling set_cookie(), you should also not use a domain name when deleting the cookie. In such a case, you can do it like this, omitting the second argument (parameter).

delete_cookie( "colourscheme" );

Cautionary Notes

  • The Provided Functions Work in Tandem

    The functions I provided above are designed to work together.

    For example, as noted above, don’t use my delete_cookie() function on cookies you set yourself with your own or some other person’s code. It may not work if the path is not set the way I did in my set_cookie() function. There may be other inter-dependencies as well.

  • Take the Usual JavaScript Precautions

    Since the code is in JavaScript, if your visitors disable JavaScript execution in their browser, your cookie code will fail. You should try to design your website so that it will still be functional and readable even if JavaScript is not available. Your site need not have all the functionality that it has when JavaScript is available, but it should still work. This is also needed for if you want your website to rank well in the search engines, since search engines operate like browsers with no JavaScript capability.

Conclusion

Armed with the above code and functions, you should be able to write JavaScripts that make use of cookies on your page without having to reinvent the wheel.

Copyright © 2008 by Christopher Heng. All rights reserved.
Get more free tips and articles like this, on web design, promotion, revenue and scripting, from http://www.thesitewizard.com/.

URI (Uniform Resource Identifier)

URI는 그것이 텍스트의 한 페이지나, 비디오 또는 사운드 클립이든, 정지 화상이든 동영상이든, 또는 프로그램이든 상관없이, 이러한 콘텐츠 들 중 어느 하나를 인식하기 위한 수단이다. 가장 보편적인 형태의 URI가 바로, 웹페이지 주소 즉, URL인데, 이는 URI의 특별한 형태이자 부분집합이라 할 수 있다. URI는 대체로 다음과 같이 설명할 수 있다.

  • 자원에 접근하기 위해 사용되는 절차
  • 어떤 자원을 가지고 있는 특정한 컴퓨터
  • 컴퓨터 상의 특정 자원의 이름 (파일 이름)

예를 들어 아래의 URI는 웹프로토콜 애플리케이션HTTP를 사용하여 액세스될 수 있는 파일을 인식하며, 그 파일은 유일한 인터넷 주소로 사상될 수 있는 www.w3.org라는 이름을 가진 컴퓨터에 존재한다.

http://www.w3.org/Icons/WWW/w3c_main.gif

컴퓨터의 디렉토리 구조에서, 그 파일은 “/Icons/WWW/w3c_main.gif"에 위치해 있다. FTP 주소와 전자우편 주소들을 인식하는 문자열들도 역시 URI이다 (그리고 HTTP 주소처럼, 이것들도 URL이라고 불리는 URI의 부분집합이다). URI의 또다른 종류 중 하나는 URN이다. URN은 "제도적인 영속성"을 갖는 URI의 한 형태로서, 그것의 정확한 위치는 때로 변할 수 있지만, 일부 에이전시가 그것을 찾을 수 있다는 것을 의미한다.

IETF의 RFC 1630에 반포된 URI 구문 규칙은 모든 인터넷 주소에 적용된다.