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 구문 규칙은 모든 인터넷 주소에 적용된다.

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 구문 규칙은 모든 인터넷 주소에 적용된다.

 http://www.itworld.com/nl/javascript/05072002

에서 참조

 

javascript Synthetic Event

In JavaScript, pretty much everything you do with respect to your
graphical user interface (GUI) has to do with detecting and reacting to
events. When the user clicks a button, to cite a popular example, the
click is represented as an event object of the click type and is passed
to whatever event handler (if any) is assigned to react to events of
that kind. Events bubble upwards through the Document Object Model (DOM)
– from, say, a button to its form to its document to its browser – and
event handlers may react to it at more than one level, if you want to
set things up that way.

The newer versions of the DOM, as implemented in Microsoft Internet
Explorer 6, allow you to use JavaScript to define and execute synthetic
events. Synthetic events are event objects that are created ex nihilo by
the JavaScript programmer, as opposed to “real” events that come into
being as a result of an action within the browser window. Synthetic
events can, for example, simulate a selection from a drop-down list box
followed by a click on a particular button, or a click on a particular
region followed by a drag between two pairs of coordinates.

Synthetic events aren’t helpful when creating auto-running
demonstrations, since the events appear to take place for no reason
(i.e., the mouse pointer doesn’t move) and, unless you put in delay
statements, the events occur in such quick succession that you can’t
tell what’s happening. Rather, synthetic events are nice for creating
test drivers that verify the behavior of interfaces. You can set up your
application so that a single button click triggers a whole series of
events, which will be run in an absolutely consistent way. This would
enable you to adjust your application to behave as required in response
to certain user behavior.

To create a synthetic event, you use the createEvent() method of the
Document object.

var e = new Event;
e = document.createEvent(“MouseEvents”);

The createEvent() method takes any of several strings as arguments;
“MouseEvents” describes a set of events associated with the mouse
pointer. A DOM reference will give you a full roster of legal
arguments.

When you’ve created an event, you need to initialize it before you turn
it loose. Here’s how to do that:

e.initEvent(“click”, true, false);

The “click” argument is one that’s significant to the “MouseEvents” set
mentioned earlier – again, consult that reference. The two Boolean
values refer to whether the event bubbles up through the DOM and whether
the event may be canceled with the preventDefault() method.

When you’ve configured your event, you can apply it to an element in the
local DOM this way:

document.myForm.myButton.dispatchEvent(e);

That simulates a click on the DOM element called myButton.

 http://www.itworld.com/nl/javascript/05072002

에서 참조

 

javascript Synthetic Event

In JavaScript, pretty much everything you do with respect to your
graphical user interface (GUI) has to do with detecting and reacting to
events. When the user clicks a button, to cite a popular example, the
click is represented as an event object of the click type and is passed
to whatever event handler (if any) is assigned to react to events of
that kind. Events bubble upwards through the Document Object Model (DOM)
— from, say, a button to its form to its document to its browser — and
event handlers may react to it at more than one level, if you want to
set things up that way.

The newer versions of the DOM, as implemented in Microsoft Internet
Explorer 6, allow you to use JavaScript to define and execute synthetic
events. Synthetic events are event objects that are created ex nihilo by
the JavaScript programmer, as opposed to “real” events that come into
being as a result of an action within the browser window. Synthetic
events can, for example, simulate a selection from a drop-down list box
followed by a click on a particular button, or a click on a particular
region followed by a drag between two pairs of coordinates.

Synthetic events aren’t helpful when creating auto-running
demonstrations, since the events appear to take place for no reason
(i.e., the mouse pointer doesn’t move) and, unless you put in delay
statements, the events occur in such quick succession that you can’t
tell what’s happening. Rather, synthetic events are nice for creating
test drivers that verify the behavior of interfaces. You can set up your
application so that a single button click triggers a whole series of
events, which will be run in an absolutely consistent way. This would
enable you to adjust your application to behave as required in response
to certain user behavior.

To create a synthetic event, you use the createEvent() method of the
Document object.

var e = new Event;
e = document.createEvent(“MouseEvents”);

The createEvent() method takes any of several strings as arguments;
“MouseEvents” describes a set of events associated with the mouse
pointer. A DOM reference will give you a full roster of legal
arguments.

When you’ve created an event, you need to initialize it before you turn
it loose. Here’s how to do that:

e.initEvent(“click”, true, false);

The “click” argument is one that’s significant to the “MouseEvents” set
mentioned earlier — again, consult that reference. The two Boolean
values refer to whether the event bubbles up through the DOM and whether
the event may be canceled with the preventDefault() method.

When you’ve configured your event, you can apply it to an element in the
local DOM this way:

document.myForm.myButton.dispatchEvent(e);

That simulates a click on the DOM element called myButton.