vanilla

If you're like me, you are always on the lookout for jQuery libraries to use, and there are thousands of them out in the wild, maybe not thousands but enough to solve just about any problem you have.

如果您像我一样,就会一直在寻找可以使用的jQuery库,并且有成千上万的jQuery库供您使用,也许不是数千,但足以解决您遇到的任何问题。

In this tutorial I'd like to show you how to build a cookie library without jQuery. Why should you build a cookie library instead of using an existing cookie library? It is important to learn the fundamentals of JavaScript.

在本教程中,我想向您展示如何在不使用 jQuery的 情况下构建cookie库。 为什么您应该建立一个cookie库而不是使用现有的cookie库? 了解JavaScript的基础很重要。

After studying this tutorial you can go back to using any jQuery cookie library but deep down you’ll be satisfied, knowing you can go through the library source code without JavaScript fatigue. Even if you never use your own cookie library, you’ll have a better understanding of how each one you use functions internally.

在学习了本教程之后,您可以回到使用任何jQuery cookie库的方式,但是从头开始,您会满意的,因为您知道自己可以遍历该库的源代码而不会感到JavaScript疲劳。 即使您从不使用自己的cookie库,也将更好地了解您使用的每个cookie内部功能。

We’ll cover the following:

我们将介绍以下内容:

  1. Creating a cookie.创建一个cookie。
  2. Reading a cookie.读取cookie。
  3. Checking for an existing cookie.检查现有的cookie。
  4. Listing all cookies.列出所有cookie。
  5. Removing a cookie.删除Cookie。

Ready? Let's dive in!

准备? 让我们潜入吧!

什么是饼干? ( What are cookies? )

Cookies are data stored in small text files, on your computer. If a server sends a web page to a browser, the connection is shut down, and the server forgets everything about the user and the browser. Cookies were designed to answer the question "How does the server remember information about the user?".

Cookies是存储在计算机上的小型文本文件中的数据。 如果服务器将网页发送到浏览器,则连接将关闭,并且服务器会忘记有关用户和浏览器的所有信息。 Cookies旨在回答以下问题:“服务器如何记住有关用户的信息?”。

先决条件 ( Prerequisites )

Note:

注意事项

  1. Important words are highlighted.Important words突出显示。
  2. Bold words emphasise a point.粗体字强调了重点。
  3. Previous / Next code appears like this . . . .上一个/下一个代码显示如下. . . . . .

There are not many prerequisites for this project because we will make use of CodePen for demos and the full code for this tutorial is on Github. You can follow the demo or setup a new CodePen. You will need to have a fair understanding of JavaScript context and methods. In addition, you will need a local HTTP server e.g. (Node.js, PHP, Python or BrowserSync).

该项目的前提条件并不多,因为我们将使用CodePen进行演示,本教程的完整代码在Github上 。 您可以按照演示或设置新的CodePen进行操作 。 您需要对JavaScript上下文和方法有一定的了解。 另外,您将需要一个本地HTTP服务器,例如( Node.js , PHP , Python或BrowserSync )。

We'll start out by getting the window and document object, we'll then walk through building out core methods that will associate with the current browser cookie.

我们将从获取窗口文档对象开始,然后逐步构建与当前浏览器cookie关联的核心方法。

@media (max-width: 1280px) { .go-go-gadget-react img:first-child { display: none; } }@media (max-width: 780px) {.go-go-gadget-react { flex-direction: column; }.go-go-gadget-react img { margin-left: 0 !important; margin-bottom: 12px !important; }.header-thingy { margin-top: 20px; }.button-thingy { margin-left: 0 !important; margin-top: 12px !important; }} @media (max-width: 1280px) { .go-go-gadget-react img:first-child { display: none; } }@media (max-width: 780px) {.go-go-gadget-react { flex-direction: column; }.go-go-gadget-react img { margin-left: 0 !important; margin-bottom: 12px !important; }.header-thingy { margin-top: 20px; }.button-thingy { margin-left: 0 !important; margin-top: 12px !important; }}

建立 ( Setup )

Let's setup our cookie library. First, create a file cookie.js, this file hold our methods, and open with Sublime Text (or Atom, VIM, WebStorm).

让我们设置我们的cookie库。 首先,创建一个文件cookie.js ,该文件包含我们的方法,并使用Sublime Text (或AtomVIMWebStorm打开

$touch cookie.js && open cookie.js -a 'Sublime Text'

Inside the file we'll add an IIFE (Immediately-Invoked Function Expression) that takes in two parameters, document and window object.

在文件内部,我们将添加一个IIFE(立即调用函数表达式) ,该函数带有两个参数,即文档窗口对象。

The if / else statement checks if Node.js, AMD is defined otherwise set it to window.

if / else语句检查是否定义了Node.js和AMD,否则将其设置为window

Note: The window object has the document object in it and contains properties like navigator, print, history, etc.

注意 :window对象中包含document对象,并且包含诸如navigatorprinthistory等属性。

cookie.js

cookie.js

(function (document, window) {'use strict';// our cookiet object will be here.. . .if (typeof define === 'function' && define.amd) {define([], function () {return cookiet;});} else {window.cookiet = cookiet;}
}(document, window));

To test if the script works, you'll need to include the cookie.js file in a HTML file and you can add a console.log('yeet! It works!'). You'll need to have a local server running because cookies does not work with file:// URI scheme. I will be using Python Server, but you can use any one you'd like.

要测试脚本是否有效,您需要在HTML文件中包含cookie.js文件,并可以添加console.log('yeet! It works!') 。 您需要运行本地服务器,因为cookie不适用于file:// URI方案。 我将使用Python Server ,但您可以使用任意一个。

$touch index.html && open index.html -a 'Sublime Text'

index.html

index.html

<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><title>cookie</title></head><body><script src="./cookie.js"></script> </body>
</html>

cookie.js

cookie.js

. . .console.log('yeet! It works!');. . .

Here is how to start Python server with Python 2.7. Navigate to the folder where your cookie.js and index.html exist and run:

这是使用Python 2.7启动Python服务器的方法。 导航到cookie.jsindex.html所在的文件夹并运行:

$ python -m SimpleHTTPServer 8000

Now open your web browser (Google Chrome preferably), and open your Developer Tools > Console, you should see yeet! It works! on your console.

现在,打开您的网络浏览器(最好是Google Chrome),然后打开“ Developer Tools > Console ,您应该会看到的yeet! It works! yeet! It works! 在您的控制台上。

Just to recap: you should have index.html and cookie.js files opened in your favorite text editor, and a Python Server (or any other server running).

回顾一下:您应该在自己喜欢的文本编辑器中打开index.htmlcookie.js文件,并拥有一个Python Server (或任何其他正在运行的服务器)。

All done? Sweet let's get started with building out the methods.

全做完了? 亲爱的,让我们开始建立方法。

读 ( Read )

To code the read method we need to first create a containing object if you remember we exported an object window.cookiet = cookiet; in the setup section above. Create the cookiet object below the 'use strict' line.

要编写read方法,我们需要首先创建一个包含对象(如果您还记得我们导出了一个对象window.cookiet = cookiet; 在上面的设置部分。 在“严格使用”行下方创建cookiet对象。

. . .
'use strict';// our cookiet object will be here.
var cookiet = {};. . .

With the cookiet object created, let's code out the read method.

创建cookiet对象后,让我们编写出read方法。

. . .var  cookiet = {read: function(params) {var name = params.name;// If there's no cookie name / key provided return undefined.if (!name) return;// split the cookie into two by using '=', and assigns// an array to `parts variable`.var parts = document.cookie.split(name + '=');// check the length of parts, since it should be cookie name // and cookie value and decodes the tokenif (parts.length === 2) return decodeURIComponent(parts.pop().split(';').shift());// Force a return of undefined if not foundreturn;},
};. . .

The read method requires an object with a property of cookie name e.g. ({ name: 'hi' }) passed into it. We check if the cookie name was provided, if it's not we return undefined. Since cookie is a document property we use the .split method on it by providing the cookie name passed into the function with string concat + and =. You might be wondering, what's happening? Hold on tight, let's look at a sample cookie string.

read方法需要将具有cookie名称的属性(例如( { name: 'hi' } )传递给它的对象。 我们检查是否提供了cookie名称,如果没有提供,则返回undefined 。 由于cookie是文档属性,因此我们在它上使用.split方法,方法是使用字符串concat +=来提供传递给函数的cookie名称。 您可能想知道,这是怎么回事? 稍等,让我们看一下示例cookie字符串。

document.cookie
"hi=again; hello=world" // output

In the code above document.cookie is a string containing a semicolon-separated list of all cookies (i.e. key=value pairs), joined by =. hi=again; is a cookie.

在上述代码中, document.cookie是一个字符串,其中包含所有cookie的分号分隔列表(即,键=值对),并由=hi=again; 是一个cookie。

The if checks the length and then decode the cookie value using decodeURIComponent method. If the cookie with the name provided is found, we return it. If not we return undefined. If you don't understand what .pop, .shift() does, I recommend you read them up.

if检查长度,然后使用decodeURIComponent方法对cookie值进行解码。 如果找到具有提供名称的cookie,我们将其返回。 如果没有,我们返回undefined 。 如果您不了解.pop.shift()功能,建议您阅读它们。

Whew! That was mouthful.

ew! 那是满口的。

创造 ( Create )

The create method takes in params object, and we check to see if the property values exists using the || logical operator. If it does not exist we set an alternative false or ' ' value.

create方法接受params对象,然后使用|| logical operator检查属性值是否存在。 || logical operator 。 如果不存在,我们设置一个替代的false or ' '值。

Next, we check for the cookie name if it is false we return false, else we encodeURIComponent the cookie name and value to ensure they do not contain any commas, semicolons, or whitespace. Set path specified or use default, path must be absolute. Set domain (e.g., 'example.com' or 'subdomain.example.com') if not specified, defaults to the host current document location. Set secure to only transmitted over secure protocol as https (SSL). Using the httpOnly when generating a cookie helps mitigate the risk of client side script accessing the protected cookie.

接下来,我们检查cookie名称,如果它为false,则返回false ,否则我们对cookie名称和值进行编码 ,以确保它们不包含任何逗号,分号或空格。 设置指定的path或使用默认值,路径必须是绝对的。 如果未指定,则设置domain (例如,“ example.com”或“ subdomain.example.com”),默认为主机当前文档位置。 将secure设置为仅通过安全协议以https(SSL)传输。 生成cookie时使用httpOnly有助于减轻客户端脚本访问受保护cookie的风险。

. . .read: function(params) {...},
create: function(params) {params.name = params.name || false; // cookie name / keyparams.value = params.value || ''; // cookie valueparams.expires = params.expires || false; // cookie expires (days)params.path = params.path || '/'; // cookie path. defaults to '/' the whole website.if (params.name) {var cookie = encodeURIComponent(params.name) + '=' + encodeURIComponent(params.value) + ';';var path    = 'path=' + params.path + ';';var domain  = params.domain ? 'domain=' + params.domain + ';' : '';var secure  = params.secure ? 'secure;' : '';var httpOnly  = params.httpOnly ? 'httpOnly;' : '';var expires = '';// If the params object contains expires in days.if (params.expires) {// using "expires" because IE doesn't support "max-age".params.expires = new Date(new Date().getTime() + parseInt(params.expires, 10) * 1000 * 60 * 60 * 24);// use toUTCString method to convert expires date to a string, // using the UTC time zone.expires = 'expires=' + params.expires.toUTCString() + ';';}// assign all the concatenated values to document.cookie.document.cookie = cookie + expires + path + domain + secure + httpOnly;return true;}return false;
},. . .

The expires calculation isn't as complex as it looks, first convert the days specified to miliseconds. If the days provided is a string, we convert to Number using parseInt in base 10 and sum it up with new Date().getTime() current time, then assign the value to expires. e.g. (2 Days * 1000 Miliseconds * 60 Minutes * 60 Seconds * 24 Hours), will equal 1.728e+8 or (172800000) Miliseconds. If the cookie was successfully saved we return true.

expires计算并不像看起来的那么复杂,首先将指定的日期转换为毫秒。 如果提供的日期是字符串,我们使用以10为底的parseInt转换为Number ,然后将其与new Date().getTime()当前时间相加,然后将值指定为expires 。 例如( 2 Days * 1000 Miliseconds * 60 Minutes * 60 Seconds * 24 Hours ),将等于1.728e+8 or (172800000) Miliseconds1.728e+8 or (172800000) Miliseconds 。 如果cookie成功保存,则返回true

Note: If the expires is not specified it will expire at the end of the session.

注意 :如果未指定到期时间,它将在会话结束时到期。

存在 ( Exists )

The exists method is pretty straightforward, since we are checking if a cookie exist, first we check if the params object has a property name and is defined. If it's not we return undefined, if it exists we call the read method we defined above providing the params object and return true if found, otherwise we return false.

exist方法非常简单,因为我们要检查cookie是否存在,因此首先要检查params对象是否具有属性名称并已定义。 如果不是,则返回undefined ,如果存在,则调用上面提供的params对象定义的read方法,如果找到则返回true ,否则返回false

. . .read: function(params) {...},
create: function(params) {...},
exists: function(params) {// checks the `params` object for property nameif (!params || !params.name) {return;}// call the read method providing the `params` object as parameterif (this.read(params)) {return true;}return false;
},. . .

ListAsObject ( ListAsObject )

This methods gets all the cookies on for a specific domain, then split document.cookie using ; if it's defined otherwise returns an empty object. We'll need to loop through the found cookies by decrementing the length of the cookies. You'd need to split using = to get an array of length 2, then decode the cookie using decodeURIComponent method, and set the first item of the array as the object key and the second as the value. Return the cookies object when done looping.

此方法获取特定域上的所有cookie,然后使用;拆分document.cookie ; 如果已定义,则返回一个空对象。 我们需要通过减少Cookie的长度来遍历找到的Cookie。 您需要使用=进行拆分,以获取长度为2的数组,然后使用encodeURIComponent方法对cookie进行解码,然后将数组的第一项设置为对象键,将第二项设置为值。 完成循环后返回Cookies对象。

. . .read: function(params) {...},
create: function(params) {...},
exists: function(params) {...},
listAsObject: function() {var cookiesObj = {}; // an empty object to store retrieved cookies.var cookies = document.cookie ? document.cookie.split('; ') : [];var len = cookies.length; // length of keys.var cookie;if (!cookies) {return cookiesObj;}while (len--) {cookie = cookies[len].split('=');cookiesObj[decodeURIComponent(cookie[0])] = decodeURIComponent(cookie[1]);}return cookiesObj;
},. . .

去掉 ( Remove )

Removing a cookie is really easy. First we check the params object, then we call the read method we defined above providing the params object and return true if removed otherwise we return false. You can also remove cookie by specifying the path or domain. But it's safe to use the cookie name.

删除Cookie非常简单。 首先,我们检查params对象,然后调用上面定义的read方法,以提供params对象,如果删除则返回true ,否则返回false 。 您还可以通过指定pathdomain来删除cookie。 但是使用cookie名称是安全的。

. . .read: function(params) {...},
create: function(params) {...},
exists: function(params) {...},
listAsObject: function() {...},
remove: function(params) {if (!params) return;if (this.read(params)) {return this.create({name: params.name,value: ' ', // set value to empty stringexpires: -1, // reset expirespath: params.path,domain: params.domain});}return false;
}. . .

结论 ( Conclusion )

Congrats! By now you should have a more detailed understanding of how cookies work and should be able to implement other methods like getting all the keys or clearing all cookies. If you need deeper information, I recommend you check out MDN. You can find the full code for this tutorial here.

恭喜! 到目前为止,您应该对cookie的工作原理有更详细的了解,并且应该能够实现其他方法,例如获取所有密钥或清除所有cookie。 如果您需要更详细的信息,建议您查看MDN 。 您可以在此处找到本教程的完整代码。

Make sure to leave any thoughts, questions or concerns in the comments below. I would love to see them.

确保在下面的评论中留下任何想法,问题或疑虑。 我很想看到他们。

翻译自: https://scotch.io/tutorials/build-a-cookie-library-with-vanilla-javascript

vanilla

vanilla_使用Vanilla JavaScript构建Cookie库相关推荐

  1. 使用 Vanilla JavaScript 构建自定义 SPA 路由器

    介绍 在本文中,我将解释如何使用 Vanilla JavaScript 构建自定义 SPA 路由器.我必须在没有任何使用框架的情况下构建一个 UI 项目,并且必须弄清楚如何处理路由,并发现您可以轻松地 ...

  2. vanilla_如何使用Vanilla JavaScript构建钢琴键盘

    vanilla Making a playable piano keyboard can be a great way to learn a programming language (besides ...

  3. vanilla_使用Vanilla JavaScript即时搜索

    vanilla Originally posted on www.florin-pop.com 最初发布在www.florin-pop.com The theme for week #15 of th ...

  4. vanilla_包装Vanilla JavaScript软件包以在React中使用

    vanilla Complex web projects often require the use of 3rd party widgets. But what if you're using a ...

  5. vanilla_如何使用Vanilla JavaScript构建简单的全屏幻灯片

    vanilla 在本教程中,您将学习如何使用纯JavaScript创建响应式全屏幻灯片. 要构建它,我们将经历几个不同的前端技巧. 另外,当我们将鼠标悬停在幻灯片上时,我们将更进一步,自定义光标的外观 ...

  6. vanilla_使用Vanilla JavaScript的快速简单的搜索过滤器

    vanilla When building Single Page Applications a feature I frequently find myself adding is a simple ...

  7. 使用 Vanilla JavaScript 创建 Web 组件

    Web 应用程序开发是一个非常拥挤的技术领域.有不同类型的框架.库和工具.在开发 Web 应用程序时,主要目标是提供带有封装组件的高质量用户界面 (UI). 因此,当您使用 React.Vue.Ang ...

  8. vanilla_如何在Vanilla JavaScript中操作DOM

    vanilla by carlos da costa 通过卡洛斯·达·科斯塔 如何在Vanilla JavaScript中操作DOM (How to manipulate the DOM in Van ...

  9. 轻量高效的开源JavaScript插件和库 【转】

    图片 布局 轮播图 弹出层 音频视频 编辑器 字符串 表单 存储 动画 时间 其它 加载器 构建工具 测试 包管理器 CDN 图片 baguetteBox.js- 是一个简单易用的响应式图像灯箱效果脚 ...

最新文章

  1. 利用OpenCV的imread将RGB图像转化为灰度图像
  2. 上下文 及 执行上下文
  3. 【业务知识】数字档案馆建设内容
  4. getValue()方法 java_java.util.zip.CRC32.getValue()方法示例
  5. LeetCode 690. 员工的重要性(图的DFSBFS)
  6. mysql先排序再分组筛选_mysql 怎样先排序再分组
  7. 基于matlab的OFDM百度文库,基于matlab的OFDM仿真总结.doc
  8. ORACLE多表查询优化
  9. 斯威夫特山地车_斯威夫特弦乐
  10. 点扩散函数(PSF)的模型及求取
  11. 端口扫描工具是什么?端口扫描工具有什么用
  12. 子元素和后代元素的区别
  13. win7 旗舰版 秘钥 联网激活
  14. 台式机计算机无线开关在哪,电脑无线wifi开关在哪里打开
  15. 英语四级口语考试计算机考吗,听说四六级改革了,那英语四级考口语吗?
  16. Windows系统下的CMD Route路由配置
  17. 码云团队如何使用码云?
  18. 用python筛选英文txt中的单词,生僻单词
  19. 位图与普通图片的区别
  20. Android判断手机的电池状态

热门文章

  1. python----引用其他py文件中的函数
  2. GAN-overview reading note(3)Wasserstein GAN
  3. 【交互题+二分】Codeforces Round #516 E. Dwarves, Hats and Extrasensory Abilities
  4. Python 基于csv 读取文本文件提示:‘gbk‘ codec can‘t decode byte 0xbf in position 2: illegal multibyte sequence
  5. 招标过程中如何讲标?
  6. 有限元中四面体的一些积分公式
  7. 哪些APP需要做ASO优化?
  8. 全球最顶级的管理模式全在这了
  9. STM32 HAL库学习笔记1-HAL库简介
  10. HTTP,TCP,UDP,Socket,WebSocket