I'm

Developer, Designer, Photographer

GET IN TOUCH

  • Buk-gu, Busan, Republic of Korea
  • ungdoli0916@naver.com
  • Kakao ID : Ungdoli
Your message has been sent. Thank you!
(즐거웅코드) 자바스크립트 쿠키 저장/가져오기/삭제

· 즐거'웅' 코드 (Source)/HTML & CSS & JAVASCRIPT
2021. 8. 15. 15:24

반응형

[즐거'웅'코드] 목차

  1. 예제 소스
  2. 구현 예시
예제 소스
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<button onclick="cookieCheck()">모든 쿠키 확인하기</button>
 
<!-- 'cookie_test'라는 이름을 가진 쿠키의 값을 'success'로 '1'일동안 저장한다. -->
<button onclick="setCookie('cookie_test', 'success', '1');">쿠키 저장하기</button>
<button onclick="getCookie('cookie_test')">특정 쿠키 value 가져오기</button>
<button onclick="deleteCookie('cookie_test')">특정 쿠키 삭제하기</button>
 
<script>
    function cookieCheck() {
        if (!document.cookie) {
            alert('null')
        } else {
            alert(document.cookie.split(';'))
        }
    }
 
    function setCookie(cookie_name, value, days) {
        var exdate = new Date();
        exdate.setDate(exdate.getDate() + days);
 
        var cookie_value = escape(value) + ((days == null) ? '' : '; expires=' + exdate.toUTCString());
        document.cookie = cookie_name + '=' + cookie_value;
    }
 
    function getCookie(cookie_name) {
        var x, y;
        var val = document.cookie.split(';');
 
        for (var i = 0; i < val.length; i++) {
            x = val[i].substr(0, val[i].indexOf('='));
            y = val[i].substr(val[i].indexOf('='+ 1);
            x = x.replace(/^\s+|\s+$/g, '');
            if (x == cookie_name) {
                alert(y);
            }
        }
    }
 
    function deleteCookie(cookie_name) {
        document.cookie = cookie_name + '=; expires=Thu, 01 Jan 1999 00:00:10 GMT;';
    }
</script>
구현 예시
반응형