当前位置: 首页 > news >正文

vanilla_使用Vanilla JavaScript构建Cookie库

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关联的核心方法。

建立 ( 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


http://www.taodudu.cc/news/show-6309732.html

相关文章:

  • 【physx/wasm】在physx中添加自定义接口并重新编译wasm
  • excel---常用操作
  • Lora训练Windows[笔记]
  • linux基础指令讲解(ls、pwd、cd、touch、mkdir)
  • InnoDB 事务处理机制
  • 启明云端ESP32 C3 模组WT32C3通过 MQTT 连接 AWS
  • 笔记 - JavaScript - 超哥视频
  • JS知识点总结(全)
  • Vue.js + Vuex + TypeScript 实战项目开发与项目优化
  • node.js 从基础到操作数据库
  • vscode css智能补全_在 Webstorm 伤透我的心后,我决定尝试 VS Code
  • Js定时器倒计时及堆叠问题解析(附源码)
  • Webstorm干货(开发效率快到飞起!!!)
  • webstorm配置和使用
  • webstorm 风扇一直响_在 Webstorm 伤透我的心后,我决定尝试 VS Code
  • 如何使用 Javascript 截断/切片/修剪字符串中的最后一个字符?
  • 宝塔安装Jdk1.8
  • curl php 宝塔 开启_宝塔安装php失败
  • 安装宝塔后手动安装php,宝塔 安装 php扩展步骤
  • 测试工具和测试自动化
  • Linux下自动化工具
  • 自动化测试概述/自动化工具
  • 自动化测试工具简介
  • 【选型】常用的自动化测试工具
  • 如何选择合适的网络自动化工具
  • 十大最佳自动化测试工具
  • Python自动化工具(自动化操作)
  • 推荐一个强大的工作流自动化工具...
  • 自动化测试.工具
  • 常见自动化测试工具,你用过哪些?
  • 常用的自动化管理工具
  • 常用自动化构建工具
  • 测试用例和bug描述规范参考
  • 测试百科:白盒测试用例的设计(图文并茂,非常详细)
  • 常见功能测试点的测试用例集合--51testing
  • 非功能测试总览