使用纯JavaScript设置年龄验证弹出式Cookie?

时间:2019-01-27 13:03:53

标签: javascript

我正在为要求年龄验证弹出窗口的电子商务网站使用新设置。通常我会依靠Jquery来做到这一点。但是,我的新设置有其自己的复杂框架,我不想仅为这个弹出窗口而将Jquery注入网站。所以我想知道是否也可以仅使用纯JavaScript来完成?

这是我惯用的Jquery版本:https://codepen.io/anon/pen/VgarjL

这是我上面笔中的Jquery代码

$(document).ready(function(){
  // put the popup at the start of the body
  $('#ageWrapper').prependTo($('body'));

  // check if the age has already been verified
  if (($.cookie('age')) !== 'true') { $('#ageWrapper').addClass('ageConfirmed'); }

  // if the "yes" button is clicked, add a cookie and hide the popup
  $('#ageOkay').click(function() {
    $.cookie('age', 'true', { expires: 1, path: '/' });
    $('#ageWrapper').removeClass('ageUnknown');
  });

  // if the "no" button is clicked, take the user elsewhere
  $('#ageBad').click(function() {
    window.location.href='https://google.com';
  });
});

在线上甚至在堆栈溢出时都有许多jquery版本/解决方案。但是我找不到纯Javascript解决方案。

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

这是可以解决的方法。仔细看一下以了解发生了什么:

/* Prepared function that will be checking if the Cookie exists (it will be called in the next function) */
function getCookie(cname) {
  var name = cname + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.split(';');
  for(var i = 0; i <ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return;
}

/* Conditional and function to check if Cookie doesn't exist. If so, it creates the Cookie */
if (getCookie('areYouOver18') !== 'yes') {
  function createCookie(name,value,minutes) {
    if (minutes) {
        var date = new Date();
        date.setTime(date.getTime()+(minutes*60*1000));
        var expires = "; expires=" + date.toGMTString();
    } else {
        var expires = ""; // if time was not declared, the Cookie will expire next time browser closes
    }
    document.cookie = name+"="+value+";"+expires+"; path=/";
  }

  createCookie('areYouOver18', 'yes', (60*48));
  // Cookie's name is "areYouOver18"
  // Cookie's value is "yes"
  // Cookie's expiry time is "48 hours"

  yourFunction(); // The Cookie is created. Now this function can invoke modal
}

function yourFunction () {
  // your function calling modal or doing something else
}