JavaScript basics
JavaScript document.cookie
We can access or obtain the cookies in the HTML DOM document object model through document.cookie. The usage is similar to other JavaScript Document object collections. Below we prepare a simple example to present settings, clear and display cookies at once.
JavaScript document.cookie example
<script type="text/javascript">
function SetCookie(x) {
if(x=='0'){
document.cookie = "name=Jordan";
}else if(x=='1'){
document.cookie = "name=";
}
}
function ShowCookie(){
alert(document.cookie);
}
</script>
<input type="button" value="設定 Cookie" onclick="SetCookie(0);">
<input type="button" value="清除 cookie" onclick="SetCookie(1);">
<input type="button" value="Show Cookie" onclick="ShowCookie();">
function SetCookie(x) {
if(x=='0'){
document.cookie = "name=Jordan";
}else if(x=='1'){
document.cookie = "name=";
}
}
function ShowCookie(){
alert(document.cookie);
}
</script>
<input type="button" value="設定 Cookie" onclick="SetCookie(0);">
<input type="button" value="清除 cookie" onclick="SetCookie(1);">
<input type="button" value="Show Cookie" onclick="ShowCookie();">

This example will have three buttons in total to trigger the JavaScript function. The first button will trigger the SetCookie function and set a cookie with name="Jordan" in the browser. The second clear button will also trigger SetCookie( ), but the difference is that the clear button will set the value of name="", which is a symbolic meaning of clearing the cookie. The other three buttons show which cookies are currently in the browser?
The two functions in the example both use the JavaScript document.cookie attribute to set, clear, or obtain the value of the cookie. While operating this example, please make sure that the cookie in your browser is cleared. It’s okay. At most, it’s just displaying irrelevant cookies when ShowCookie. Also note that the number of cookies that can be stored in each browser is limited. If it is full, it may not work properly. Clear it if necessary. Right!
Post a Comment
0 Comments