[jQuery]マルチドメイン(同一ドメイン配下)でcookieを共有する方法と活用例

以前の記事のバージョンアップ版。

やりたいこと

独自ドメインを取得していて、サブドメインを作って、複数のWEBサイトを運営しているとする。

どれかのWEBサイトにアクセスしたら、「他のサイトもありますよ」のポップアップを出す。

一度ポップアップを表示したら、以降どのWEBサイトにアクセスしてもポップアップは出さない。

ポップアップを出さない期間は表示したタイミングから24時間とする。

動作イメージ

sessionStorageだと表示しているブラウザ(タブ)依存になるので、新規窓で開いたりブラウザを閉じたりすると持ち越せない。
localStorageだと永続的に保存されるけど手動で消さないといけない。

だからCookieでやっていきましょう。

Cookieは「ドメイン単位」になるので、サブドメインのやり取りができる。
有効期限を設けられるので作りっぱなしでも安心。

別案としてURLパラメータ、サーバー間通信とかがあるけど、URLパラメータは仕込むのが大変だし状況が限られて今回のケースに合わない。サーバー間通信ほど手間を掛けてガチガチなものは求めてない。

Cookieです。

こんな感じ

とりあえずポップアップ。

<div id="firstAccessPopup">
    <div class="wrap">
        <div class="set">
            <ul>
                <li><a href="">link01</a></li>
                <li><a href="">link02</a></li>
                <li><a href="">link03</a></li>
                <li><button type="button" class="stay">滞在継続</button></li>
            </ul>
        </div>
        <div class="bg"></div>
    </div>
</div>
#firstAccessPopup{
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 100;
    display: none;
    .wrap{
        width: 100%;
        height: 100%;
        background: rgba(255,255,255,.95);
        display: flex;
        justify-content: center;
        align-items: center;
        .bg{
            width: 100%;
            height: 100%;
            background: rgba(255, 255, 255, .95);
            position: absolute;
            top: 0;
            left: 0;
        }
        .set{
            width: calc(100% - 8vw);
            max-width: 560px;
            padding: 40px;
            background: #fff;
            position: relative;
            z-index: 1;
        }
    }
}

画面いっぱいに表示する。

通常では非表示にしておく。

で、こう。

<script src="https://code.jquery.com/jquery-3.7.1.js" integrity="sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4=" crossorigin="anonymous"></script>
<script>
$(function () {
  const cookieName = 'user_token';
  const cookieValue = 'userAccessed';
  const cookieDomain = '.sample.com'; // サブドメイン含めて共有
  const cookieExpireHours = 24;

  // Cookieが存在するかチェック
  function getCookie(name) {
    const match = document.cookie.match(new RegExp('(?:^|; )' + name + '=([^;]*)'));
    return match ? decodeURIComponent(match[1]) : null;
  }

  // Cookieがなければ設定し、ポップアップ表示
  if (!getCookie(cookieName)) {
    // 日時を設定
    const expireDate = new Date();
    expireDate.setTime(expireDate.getTime() + (cookieExpireHours * 60 * 60 * 1000));

    // Cookieを設定
    document.cookie = `${cookieName}=${cookieValue}; path=/; domain=${cookieDomain}; expires=${expireDate.toUTCString()}; Secure; SameSite=Lax`;

    // ポップアップ表示
    if ($("#firstAccessPopup").length) {
      $("#firstAccessPopup").fadeIn();
    }
    console.log(`Cookie "${cookieName}" を登録した`);
  }else{
    console.log(`Cookie "${cookieName}" は存在する`);
  }
  //滞在継続
  $('#firstAccessPopup .bg, #firstAccessPopup button.stay').on('click',function(){
    $('#firstAccessPopup').fadeOut();
  })
})
</script>
  • アクセス時にCookieがあるか調べる
  • CookieがなければCookieを設定する、ポップアップを表示する
  • Cookieがあるなら何もしない

表示・非表示の分岐を「user_token」ってcookieがあればOKにしてあるので、値の「userAccessed」はぶっちゃけどうでもいい。

実際の動作について

jsで作ってるから、読み込んでから発火するから、ポップアップは時間差で表示される。

こればっかりはjQueryだろうがバニラJSだろうが関係ない仕様なので諦めるしかない。

最初から表示するようにしたら、表示しない状況では「一瞬表示されて消える」になる。
そっちのほうが気持ち悪い。

何が何でもガチガチにやりたければphpで初期設定する方向になるんだけどどうなんでしょうね。
めんどくさいからやりたくないですね。

コメント

タイトルとURLをコピーしました