ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Cookie를 활용한 예시(모달창 생성 여부)
    [포스코x코딩온] 웹개발자 풀스택 부트캠프8기 2023. 8. 11. 22:05
    728x90

    Cookie 사용

    • 쿠키를 사용하여 경고 모달창에서 '오늘 그만 보기'를 클릭하면 모달창이 안뜨게 해보겠습니다.
    • Bootstrap Modal Component를 이용하였습니다.

    index.ejs

    • 로그인하러 가기 클릭 시 모달창 생성
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
      </head>
      <body>
        <a href="/warning">로그인하러 가기</a>
      </body>
    </html>

    warning.ejs

    • "오늘 그만보기" 체크 시 쿠키가 생성된다.
    • 그 후 쿠키가 있을 때에는 modal.hide()로 설정되어 나타나지 않는다.
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <link
          href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css"
          rel="stylesheet"
          integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65"
          crossorigin="anonymous"
        />
        <script
          src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"
          integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4"
          crossorigin="anonymous"
        ></script>
        <title>Document</title>
      </head>
      <body>
        <!-- Button trigger modal -->
        <button
          type="button"
          class="btn btn-primary"
          data-bs-toggle="modal"
          data-bs-target="#exampleModal"
          id="button"
        >
          경고창
        </button>
    
        <!-- Modal -->
        <div
          class="modal fade"
          id="exampleModal"
          tabindex="-1"
          aria-labelledby="exampleModalLabel"
          aria-hidden="true"
        >
          <div class="modal-dialog">
            <div class="modal-content">
              <div class="modal-header">
                <h1 class="modal-title fs-5" id="exampleModalLabel">안내</h1>
                <button
                  type="button"
                  class="btn-close"
                  data-bs-dismiss="modal"
                  aria-label="Close"
                ></button>
              </div>
              <div class="modal-body">
                인터넷익스플로어(IE)지원 종료 안내 <br />
                인터넷익스플로어(IE)서비스 지원이 종료되었습니다.
              </div>
              <div class="modal-footer">
                <input type="checkbox" id="stopShowing" />
                오늘 그만보기
                <button
                  type="button"
                  class="btn btn-primary"
                  data-bs-dismiss="modal"
                  id="closeModalBtn"
                >
                  닫기
                </button>
              </div>
            </div>
          </div>
        </div>
        <script>
          // 이 부분을 추가하여 체크박스의 상태를 쿠키에 저장하고, 필요한 경우 모달을 숨긴다.
          const stopShowingCheckbox = document.getElementById("stopShowing");
          const closeModalBtn = document.getElementById("closeModalBtn");
          const modal = new bootstrap.Modal(
            document.getElementById("exampleModal")
          );
    
          // 새로운 페이지에 들어갈 때 쿠키를 체크하여 모달을 숨긴다.
          window.addEventListener("DOMContentLoaded", () => {
            if (!document.cookie.includes("hideModal=true")) {
              modal.show();
            }
          });
    
          closeModalBtn.addEventListener("click", () => {
            if (stopShowingCheckbox.checked) {
              document.cookie = "hideModal=true; max-age=86400"; // 쿠키에 저장 (24시간 유지)
            }
            modal.hide();
          });
        </script>
      </body>
    </html>

     

     

    cookie.js

    const express = require("express");
    const app = express();
    const cookieParser = require("cookie-parser");
    const PORT = 8000;
    
    app.set("view engine", "ejs");
    
    app.use(cookieParser());
    
    app.get("/", (req, res) => {
      res.render("index");
    });
    
    app.get("/warning", (req, res) => {
      res.render("warning");
    });
    
    app.listen(PORT, () => {
      console.log(`http://localhost:${PORT}`);
    });

    https://github.com/DongHo-Kang/KDT-8-web/tree/8e6ef7c2bbf049ba748c9e6a6abbb9219c2c9b2b/230811_cookie_practice

     

     

     

     

    728x90
Designed by Tistory.