Home > Web Front-end > JS Tutorial > How Can I Set, Unset, and Manage Cookies with js-cookie?

How Can I Set, Unset, and Manage Cookies with js-cookie?

Linda Hamilton
Release: 2024-12-18 16:02:11
Original
497 people have browsed it

How Can I Set, Unset, and Manage Cookies with js-cookie?

Setting and Unsetting Cookies with jQuery

To manipulate cookies using jQuery, the recommended approach is no longer using the jQuery Cookie plugin. Instead, it's advised to use the standalone js-cookie library, available at https://github.com/js-cookie/js-cookie.

Setting a Cookie

To set a cookie with js-cookie:

Cookies.set('name', 'value');
Copy after login

For instance, to set a cookie named "test" with a value of 1:

Cookies.set('test', 1);
Copy after login

Unsetting a Cookie

To delete a cookie with js-cookie:

Cookies.remove('name');
Copy after login

Using the previous example, to delete the "test" cookie:

Cookies.remove('test');
Copy after login

Setting Custom Options

To set custom options for a cookie, such as expiration time or domain, pass an object as the third argument:

Cookies.set('test', 1, {
  expires: 10, // Expires in 10 days
  path: '/', // The path attribute of the cookie
  domain: 'jquery.com', // The domain attribute of the cookie
  secure: true // The secure attribute of the cookie
});
Copy after login

Reading Cookie Values

To retrieve the value of a cookie:

var cookieValue = Cookies.get('name');
Copy after login

For example, to retrieve the value of the "test" cookie:

var testValue = Cookies.get('test');
Copy after login

The above is the detailed content of How Can I Set, Unset, and Manage Cookies with js-cookie?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template