Coder Social home page Coder Social logo

jaywcjlove / cookie.js Goto Github PK

View Code? Open in Web Editor NEW
182.0 13.0 55.0 624 KB

:cookie: A simple, lightweight JavaScript API for handling browser cookies , it is easy to pick up and use, has a reasonable footprint(~2kb, gzipped: 0.95kb), and has no dependencies. It should not interfere with any JavaScript libraries or frameworks. https://jaywcjlove.github.io/cookie.js/

Home Page: https://jaywcjlove.github.io/cookie.js

JavaScript 100.00%
cookie mdn-cookies umd esm javascript cookies

cookie.js's Introduction

JavaScript Cookie

Buy me a coffee Downloads Build & Test Coverage Status README-zh.md

🍪 A simple, lightweight JavaScript API for handling browser cookies, it is easy to pick up and use, has a reasonable footprint (~2kb) (gzipped: 0.84kb), and has no dependencies. It should not interfere with any JavaScript libraries or frameworks.

Old v1 version document preview.

Features:

🚀 Has no dependencies
🌱 Works in all browsers
🍁 Support TypeScript, including d.ts definition
🔥 Heavily tested
📦 Supports AMD/CommonJS
💥 cookie.min.js 2.01kb(gzipped: 0.84kb)

Usage

Installed via npm. You will need Node.js installed on your system.

$ npm install cookiejs --save
import cookie from 'cookiejs';

cookie("test", "tank", 1)

Or manually download and link cookiejs in your HTML, It can also be downloaded via UNPKG or jsDelivr CDN:

<script src="https://unpkg.com/cookiejs/dist/cookie.min.js"></script>
<script type="text/javascript">
  cookie("test", "tank", 1);
</script>

Basic Usage

cookie(key, value, num)

key cookie name
value cookie value
num expires time

cookie('test', 'tank', 1)    // Create a cookie that expires 1 days from now
cookie('test')               // Create a cookie, valid across the entire site
cookie('test', null)         // Delete cookie `test`
cookie()                     // Get all cookie

cookie.set('test', 'tank', 1) // ====cookie('test', 'tank', 1)
cookie.get('test')            // ====cookie('test')
cookie.remove('test')         // ====cookie('test',null)
cookie.remove('test3', 'test4') // Delete cookie `test3` and `test4`

cookie.clear()                // Clean all cookie
cookie.all()                  // Get all cookie

Set Cookie

cookie.set(name, value, options)
The same effect cookie(name, value, options)

Set the value of the cookie in batches

cookie.set({
  name1: 'value1',
  name2: 'value2'
});

Create cookie that expires 30 days from now

cookie('test', 'tank', 30);  // Create a cookie that expires 30 days from now

cookie({ 'test':'123', 'test2':'456' }, { // 批量设置
  'expires': 30,
  'path': '/',
  'domain':''
});

Create cookie that expires 30 days from now,and set cookie attributes

cookie('test', '123', { 'expires': 30, 'path': '/', 'domain':'' });

Cookie Attributes

individually for each call to cookie.set(...) by passing a plain object in the last argument. Per-call attributes override the default attributes.

Examples:

cookie('name', 'value', { 'expires': 30, 'path': '/', 'domain':'' });
cookie.get('name')
cookie.remove('name')

expires

Define when the cookie will be removed. Value can be a Number which will be interpreted as days from time of creation or a Date instance. If omitted, the cookie becomes a session cookie.

cookie('name', 'value', { 'expires': 30 });

path

Default: /

A String indicating the path where the cookie is visible.

cookie.set('name', 'value', { path: '' });
cookie.get('name'); // => 'value'

domain

Default: Cookie is visible only to the domain or subdomain of the page where the cookie was created, except for Internet Explorer (see: Note regarding Internet Explorer default behavior).
⚠️If you omit the domain attribute, it will be visible for a subdomain in IE.

A String indicating a valid domain where the cookie should be visible. The cookie will also be visible to all subdomains.

Examples:

cookie.set('name', 'value', { domain: 'subdomain.website.com' });
cookie.get('name'); // => undefined (need to read at 'subdomain.website.com')

secure

Default: No secure protocol requirement.

Either true or false, indicating if the cookie transmission requires a secure protocol (https).

Here's an examples:

cookie.set('name', 'value', { secure: true });
cookie.get('name'); // => 'value'
cookie.remove('name');

SameSite

The SameSite attribute lets servers specify whether/when cookies are sent with cross-site requests (where Site is defined by the registrable domain and the scheme: http or https). This provides some protection against cross-site request forgery attacks (CSRF). It takes three possible values: Strict, Lax, and None.

With Strict, the cookie is only sent to the site where it originated. Lax is similar, except that cookies are sent when the user navigates to the cookie's origin site. For example, by following a link from an external site. None specifies that cookies are sent on both originating and cross-site requests, but only in secure contexts (i.e., if SameSite=None then the Secure attribute must also be set). If no SameSite attribute is set, the cookie is treated as Lax.

Here's an example:

cookie.set('name', 'value', { sameSite: 'Strict' });

Note: The standard related to SameSite recently changed (MDN documents the new behavior above). See the cookies Browser compatibility table for information about how the attribute is handled in specific browser versions:

SameSite=Lax is the new default if SameSite isn't specified. Previously, cookies were sent for all requests by default.

  • Cookies with SameSite=None must now also specify the Secure attribute (they require a secure context).
  • Cookies from the same domain are no longer considered to be from the same site if sent using a different scheme (http: or https:).

Related

  • storejs A simple, lightweight JavaScript API for handling browser localStorage , it is easy to pick up and use, has a reasonable footprint 2.36kb(gzipped: 1.04kb), and has no dependencies.

Contributors

As always, thanks to our amazing contributors!

Made with action-contributors.

License

Licensed under the MIT License.

cookie.js's People

Contributors

dependabot[bot] avatar dmison avatar jaywcjlove avatar renovate[bot] avatar root-io avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cookie.js's Issues

cookie("test",null)错误

cookie("test",null)         //删除cookie test

这句应该是执行了 cookie.clear() ,删除所有吧

var cookie = function(name, value, options) {
        var argm = arguments;
        if (argm.length === 0) return Cookie().clear();
        if (argm.length === 2 && !value) return Cookie().clear(name);
        if (typeof name == "string" && !value) return Cookie().get(name);
        if (isPlainObject(name) || argm.length > 1 && name && value) return Cookie().set(name, value, options);
        if (value === null) return Cookie().remove(name);
        return Cookie().all();
    };

还有

cookie("test","tank",1800)  //设置 cookie 的值,生存时间半个小时

这个也有问题

Spurious "[expires] is read-only" exception

Using cookiejs v2.1.0 I get the following spurious exception: Uncaught TypeError: "expires" is read-only

This occurs when attempting to set a cookie e.g. cookie.set('test', 'true', { expires: 1, })

Or attempting to remove a cookie e.g. cookie.remove('test')

This issue resolves if switching back to cookiejs v2.0.0

大佬,有个小建议

今天在学习插件的封装,所以研究了你的一些插件封装的思路,从你的代码里面获益匪浅,在这例发现一个问题,就是每次调用cookie()的时候都会去执行:

function Cookie() {
        if (!(this instanceof Cookie)) {
            return new Cookie();
        }
}

意味着每次都会创建一个新的实例,这样做在设计和性能方面都不是很好,我建议最好只创建一个实例就可以了。可以做如下改装:

function Cookie() { }
function init() {
        if ( !this.instance ){         
            this.instance = new Cookie();
        }     
        return this.instance; 
}

var cookie = function(name,value,option) {
        var arg = arguments;
        if(arg.length === 0) return init().all();
}

不知道我的思路怎么样?

api 更新

unescape 和 escape 已经被弃用。应该可以使用 encodeURI 和 decodeURI 代替?

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Other Branches

These updates are pending. To force PRs open, click the checkbox below.

  • chore(deps): update actions/checkout action to v4
  • chore(deps): update actions/setup-node action to v4
  • chore(deps): update peaceiris/actions-gh-pages action to v4

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/ci.yml
  • actions/checkout v3
  • actions/setup-node v3
  • peaceiris/actions-gh-pages v3
  • ncipollo/release-action v1
npm
package.json
  • @rollup/plugin-commonjs ^24.0.1
  • @rollup/plugin-json ^6.0.0
  • @rollup/plugin-node-resolve ^15.0.1
  • @rollup/plugin-terser ^0.4.0
  • bannerjs ^3.0.1
  • rollup ^3.17.3
  • rollup-plugin-sizes ^1.0.5
  • tsbb ^4.1.5

  • Check this box to trigger a request for Renovate to run again on this repository

Expose the cookie as a string

I would love to get the cookie as a string instead of only having document.cookie set. I need to set cookies using the Set-Cookie header, server side.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.