Simply create a cookie with JS cookie

By ,
Published on February 24, 2018
JavaScript (JS)

I recently had to create a small cookie for a commercial website. I was trying to save users session datas, to send its to a third party plugin later. So I was going to store there data in the browser of each visitors. That’s the goal of a cookie : small text file stored on the client terminal. However I never had set any cookie yet (except  some chocolate cookies, but that is an other recipe).

After some researches, I found that amazing and small library named JS Cookie on Github. (The former version is named jQuery cookie, not supported anymore).

To use this  script, you ‘ll just need to load a single and lightweight JS file. This library contains some functions very useful to manage any cookie easily on your website. (the former version required the call of two libraries : jQuery and jQuery cookie).

<!-- First host the file js.Cookie.js, Then, you just need to call it on your website -->
<script src="/path/to/js.cookie.js"></script>
<!-- For a quick use, you also can use this hoster version of the library -->
<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>

Now you can easily configure, delete or change any cookie easily.

/* Let's try to set a new cookie for 7 days */
var value = 'my favorite cookie';
Cookies.set('name', value, { expires: 7 });
/* Now I want to get data from a specific cookie */
Cookies.get(); // => { name: 'value' }
/* Finally, I'll deleate my cookie */
Cookies.remove('name');

To check if your cookie is well set, you should use a plugin in your browser that let you overview the cookies of any website. In Google Chrome, I advise you the “EditThisCookie” plugin.

Now it’your turn to set your first cookie 🙂 Keep in mind there are rules and policies to follow, depending of your country.

Poster un Commentaire

avatar
  Subscribe  
Notify of