COOKIES + 3rd Party & | GET / SET / C O O K I E S (intellij)*

+ REACT

RESOURCES

  • Cookies
  • save , read , erase – https://clickety-clack.click/cookies-save-read-erase/

Understand CookiesGET cookiesSET cookies3rd Party Cookies

https://iq.opengenus.org/cookies/

Cookies are the most commonly used technique by which websites store information on a user's browser. This has its own advantages such as personalized browsing, more relevant content and others along with some disadvantages such as activity tracking. In this article, you will understand:

  • The basic idea of cookies
  • Different types of cookies like third party and persistent
  • How to set, get and delete cookies in JavaScript?
  • How to view cookies? and how the World looks at it?
  • A demo to understand the inner workings of cookies
What are Cookies?

A cookie is a small amount of text information given by the web server to web browser. This helps the server differentiate a first-time user from a regular user.
This data is stored on the visitor's hard drive, and is retrieved each time the browser visits the specific website. A cookie can only be retrieved and read by the domain that has placed it on the visitor's machine.

According to the definition provided by Microsoft:

A Cookie is a small text based file given to a user by a visited website that helps identify the user to that site. Cookies are used to maintain state information as the user navigates different pages on a Web site or return to the Web site at a later time.

Web browsing is personalised by the use of cookies, and they may also enable quicker access to some websites.

Temporary vs Persistent Cookies

A temporary cookie is one which is removed from the visitor's local hard drive as soon as the browser is closed or the session expires. These are also called session cookies.

Persistent cookies are stored in the visitor's hard drive, even after the browser is closed. This helps in uniquely identifying the web browser on subsequent visits.

First-Party vs Third-Party Cookies

Cookies that originate from the host domain are first-party cookies.These usually store the preferences of the visitor while visiting the website.
Cookies that originate from any other domain are third-party cookies. If there are ads on a website served by a third-party, cookies are served alongside, and saved to the visitors machine. These are usually used for advertising or marketing purposes.

How to Set Cookies?

Cookies come in name-value pairs, like: name=John.
To set a cookie in JavaScript:

document.cookie = "cookiename=cookievalue"


Js

You can add an expiry date so that the particular cookie will be deleted on that date:

document.cookie = "cookiename=cookievalue;expires=Sun, 21 Jul 2019 14:00:00 IST"


Js

Function to create a cookie:

function createCookie() 
{
    var d = new Date();
    d.setTime(d.getTime() + (30 * 24 * 60 * 60 * 1000));
    document.cookie = document.getElementById("name").value + "=" + document.getElementById("value").value + ",expires=" + d.toUTCString() + ",path=/;";
    alert(document.cookie);
}


HTML

How to Get Cookies?

One can get cookies using the cookie property of document as follows:

var x = document.cookie


Js

How to Delete Cookies?

To delete a cookie, just set the values of the cookie empty, and set the expiry date to a date which has passed:

document.cookie = "cookiename=;expires=Mon, 01 Jul 2019 14:00:00 IST"


Js

Function to delete a cookie:

function deleteCookie() 
{
    var name = document.getElementById("delete").value;
    var cookie = getCookie(name);
    var d = new Date('January 01, 2001 00:00:01');
    document.cookie = name + "=,expires=" + d.toUTCString() + ",path=/;";
}


HTML

Cookies are text strings. However, if you create a new cookie, the old cookie is not overwritten, but added to the old string:

document.cookie = "firstName=John;expires=Sun, 21 Jul 2019 14:00:00 IST"


Js

The cookie string right now: firstName=John

document.cookie = "lastName=Smith;expires=Sun, 21 Jul 2019 14:00:00 IST"


Js

The cookie string right now: firstName=John lastName=Smith

How to view Cookies?
  • Set by your website

Open Developer Tools, go to Application, and check cookies for separate domains.

  • Set by some website on your machine

In Privacy settings of your browser, select Cookies, and view individual cookies set by different websites.

With the increased concerns regarding digital privacy, internet fraud, and confidentiality, cookies have come under much heat.

However, it is worthwhile to note that cookies cannot execute or run programs on your system. Cookies are simple text files which usually contain the name of the web browser, domain, path, expiration date, etc. There is no executable text in a cookie.

Since a cookie can only be read by the server placing it, data security becomes an issue if someone else has access to the system, or the website itself is hacked.

In the cyber security industry, it has been a common perception that third-party cookies are potentially more intrusive than first-party cookies, as they may pass the user's data to some other websites.

So it is a recommended practice to disable third-party cookies and only enable first-party cookies. The cookies can also be deleted from the machine's hard drive regularly, which may, however, lead to lesser quality of web-browsing.

Example to demonstrate working of cookies

Consider this web page where we are setting a cookie (you can download the code in a file named code.html and open it in a web browser like Google Chrome to follow along, Note: you may need to serve the page using a local server):

<!DOCTYPE html>

<head>
    <script>
        //create a cookie
        function createCookie() {
            var d = new Date();
            d.setTime(d.getTime() + (30 * 24 * 60 * 60 * 1000));
            document.cookie = document.getElementById("name").value + "=" + document.getElementById("value").value + ",expires=" + d.toUTCString() + ",path=/;";
            alert(document.cookie);
        }
        
        //delete a specific cookie
        function deleteCookie() {
            var name = document.getElementById("delete").value;
            var cookie = getCookie(name);
            var d = new Date('January 01, 2001 00:00:01');
            document.cookie = name + "=,expires=" + d.toUTCString() + ",path=/;";
        }

        //get specific cookie
        function getCookie(cname) {
            var search = cname + "=";
            //to handle cookies with special characters in them use decodeURIComponent
            var decoded = decodeURIComponent(document.cookie);
            var ca = decoded.split(",");
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) == ' ')
                    c = c.substring(1);

                if (c.indexOf(name) == 0)
                    return c.substring(name.length, c.length);
            }
            return "";
        }

        //display all cookies
        function displayAllCookies() {
            alert(document.cookie);
        }
    </script>
</head>

<body>
    <form onsubmit="return createCookie()">
        Name: <input id="name" type="text">
        Value: <input id="value" type="text">
        <input type="submit" value="Create Cookie">
    </form>
    <p>
        <button type="button" onclick="displayAllCookies()">Display All Cookies</button>
    </p>
    <form onsubmit="return deleteCookie()">
        Name: <input id="delete" type="text">
        <input type="submit" value="Delete Cookie">
    </form>
</body>

</html>


HTML

Once the cookie has been set, the following alert is shown by the browser:

Create First Cookie

It will show another alert:

Create Second Cookie

The cookies will look like this in the Chrome Developer Tools. Use Ctrl+Shift+i to open the same.

Chrome Developer Tools

You can delete the cookies in the form using the delete field and you will see the changes reflected in the Chrome developer console:

Delete Cookie

Note: Some browsers, including Google Chrome, do not store cookies set by static HTML pages. Serve them on a remote server, or create a development environment like localhost and run the files on them to view the set cookies.

https://www.tabnine.com/academy/javascript/how-to-get-cookies/

JavaScript – How to Get Cookies Using JavaScript

Cookies make it possible to store information about a web application’s user between requests.

After a web server sends a web page to a browser, the connection shuts down and all information held by the server is lost. This means that information cannot easily be persisted between requests, as at each new request the server will not have any local context on the user. Cookies overcome this obstacle by storing the required information on the user’s computer in the form of a name=value string.

Cookies are often used to store usernames, preferences, access passwords, etc.

Note: You should always keep *security* in mind when storing sensitive information like passwords. The information stored in cookies is stored as a plain string, and can be easily discovered with minimal technical knowledge.

To learn more about cookies check out this link.

Get cookies

Getting all of the cookies from a user’s machine is very simple. Just call document.cookie to retrieve the current value of all cookies. You can then store this value in a variable for further manipulation.

document.cookie = "username=Debra White; path=/";

document.cookie = "userId=wjgye264s; path=/";

let cookies = document.cookie;

console.log(cookies); // expected output: username=Debra White; userId=wjgye264s

In the above code, the first two lines of code set the values of two different cookies – username, and userId. The third line retrieves both cookies and stores it to a variable named cookies.

To learn more about cookies, and setting a cookie, check out this link.

Getting a specific cookie is a little more complex than retrieving all cookies, but not that big of a deal.

If you have the cookie’s name, all you need is a function that iterates through all of the user’s cookies and finds the specific cookie required. The code sample below defines a function, getCookie(), that takes the name of a cookie and returns that cookie’s value:

function getCookie(cName) {

const name = cName + "=";

const cDecoded = decodeURIComponent(document.cookie); //to be careful

const cArr = cDecoded.split('; ');

let res;

cArr.forEach(val => {

if (val.indexOf(name) === 0) res = val.substring(name.length);

})

return res

}

Exploring function getCookie() by line

The function getCookie takes a cookie’s name as a parameter, then performs the following steps:

  1. The first line assigns the requested cookie name to a constant variable name. It appends an equals sign to the end of the name. For example, passing in a cookie value ‘username’ will result in ‘username=’ being stored in the name variable.
  2. The next line retrieves all of the cookies using document.cookie, then applies decodeURIComponent() to the result. This function “cleans” the string from “encoding traces” that may have been included in the cookie content. You have likely seen these encoding traces before, they look similar to this: %20%24username%20.
  3. As explained in the previous section, document.cookie returns results as a string containing all cookie values separated by semicolons (;). Here I have used the split() method, asking it to split the string’s values apart when it encounters a semicolon followed by a blank space. The result will be an array of cookie strings.
  4. The following two lines define the return variable, res, and call the forEach() method on the array of cookies obtained in line 4 (cArr). The forEach() iterates through an array, executing a callback function once for each array element. In the above example, if the value stored in variable name appears at the beginning of the string (i.e. at index 0), the inner block assigns the content of the cookie (i.e. the value after the “=” sign) to the variable res. The value length is larger than index by one. This allows us to trim off both the full string name of the cookie, and the trailing equality sign by starting the trim at index = name.length. For trimming I used the substring() method, which produces a substring of the specified length from the original input string.
  5. If the forEach() method was not able to find the requested cookie, the value ‘undefined’ will be returned.

Keep in mind that in many cases, working with cookies will begin with fetching a cookie’s value, and then requesting information from the user if the requested cookie is not found. The final result of the user’s input will be stored back to the user’s cookies. To learn more about cookies, and setting a cookie, visit this link.

Related Articles:

JavaScript – How to Use Cookies

JavaScript – How to Use the String length Property

JavaScript – How to Use The Array forEach() Method

https://www.tabnine.com/academy/javascript/how-to-set-cookies-javascript/

 

JavaScript – How to Use Cookies with JavaScript

Cookies make it possible to store information about a web application’s user between requests.

After a web server sends a web page to a browser, the connection shuts down and all information held by the server is lost. This makes maintaining user state challenging, as we cannot refer to the server for values specific to the current user’s browser activity. Cookies overcome this obstacle by storing the required information on the user’s computer in the form of a name=value string.

Cookies are often used to store usernames, preferences, authentication tokens, and other similar items.

It is important to keep *security* in mind when storing sensitive information like authentication tokens. Cookies can be seen and modified by the user, potentially exposing sensitive information. For more about this issue see the section Set a path for a cookie below.

Setting a cookie uses the following syntax:

document.cookie = ‘newCookie’

Let’s break this down into its components:

  • document.cookie is the command used to create a new cookie.

  • ‘newCookie’

    is a string that sets the cookie

    value

    . It has its own syntax to be aware of:

    name=value

    • For readability reasons name should imply what the cookie stores (e.g. username)
    • value is simply the value.

Below is an example of setting a cookie using this syntax:

document.cookie = "username=Max Brown";

The above code will store a cookie named “username” with the value “Max Brown”.

Note: Cookies expire automatically based on an expiration date that can be set in code. If no expiration date is set, the cookie will be deleted as soon as the browser is closed. The next section covers setting an expiration date for your cookies.

By default, cookies will be automatically deleted once the browser is closed. This prevents users from re-using the cookie values on subsequent visits to your page. You can override this by setting an expiration date for your cookie. This can be done easily by adding expires=expirationDate in UTC separated by semicolon from the name=value, as seen in the following example:

document.cookie = "username=Max Brown; expires=Wed, 05 Aug 2020 23:00:00 UTC";

The above example sets the “username” cookie to “Max Brown” as before, but it also adds an expiration date of Wednesday, August 5th, 2020, with an expiration time of 23:00:00 UTC. When this expiration time is reached, the cookie value will be deleted.

Note: UTC is a time standard (the coordinated universal time).

By default, cookies are associated with the page that sets them. This can lead to cookie values that are very easily traced by a curious user using developer tools. AS such, it is not advisable to store sensitive data on the root path for your application. Instead, you can provide a path where this data should be stored. The syntax for this is as follows:

document.cookie = "username=Max Brown; expires=Wed, 05 Aug 2020 23:00:00 UTC; path=/"

In the above example, we have set our “username” cookie with the value of “Max Brown”, and set its expiration to the same date as before. The difference is the path parameter, which modifies where the cookie is stored on the user’s machine. This is very useful when trying to store sensitive information, as it makes the information harder to find.

setCookie function

All of the above examples hard-code the cookie values, which will be of limited utility in most cases. Cookie values can also be set using a JavaScript function. Take the following code for example:

let username = 'Max Brown';

// Set a Cookie

function setCookie(cName, cValue, expDays) {

let date = new Date();

date.setTime(date.getTime() + (expDays * 24 * 60 * 60 * 1000));

const expires = "expires=" + date.toUTCString();

document.cookie = cName + "=" + cValue + "; " + expires + "; path=/";

}

// Apply setCookie

setCookie('username', username, 30);

This code defines a function, setCookie(). This function will create a cookie with the name “username”, value “Max Brown” with an expiration date of 30 days from the time it was created. Let’s explore this function line-by-line:

  1. In the first line of the function body, variable date is created and given the current date and time value in UTC as its initial value, This UTC timestamp will be formatted using the UTC timestamp format (e.g. Thu Aug 06 2020 12:41:34 GMT+0000 (UTC)). This value may be adjusted based on the user’s time zone.
  2. The next line of code converts the UTC timestamp above into a number (E.g. 1599308841783). This number is an integer known as the “epoch” time, or Unix time unit, and can be converted to a UTC timestamp easily. This allows us to easily manipulate the time using integer time differentials. The second part of this row uses this epoch time to calculate an expiration date for the cookie. It requires the number of milliseconds that you want your cookie expiration to take. The above code converts the parameter expDays (with a value of 30 as passed in above), and converts those requested days into an equivalent number of milliseconds. These milliseconds are then added to the Unix epoch timestamp, creating the target expiration date and time for our cookie.
  3. The third line declares a new variable expires, and gives it the value calculated for the expiration date in the previous line. This value is converted into a UTC string, which always shows GMT time as opposed to local time (e.g. Sat, 05 Sep 2020 12:38:16 GMT).
  4. The final line of the function sets the new cookie with all of the parameters populated:
    username=Max Brown; expires=Sat, 05 Sep 2020 12:38:16 GMT; path=/

To update a cookie, simply overwrite its value in the cookie object. You do this by setting a new cookie on the document with the same *Name*, but a different *Value*. The following code shows this in action:

username = 'Jen Brown';

setCookie('username', username, 30);

In the above code, we did not create a new cookie, as we already have a value in the cookie “username” of “Max Brown”. This call to setCookie() overwrites the value of the “username” cookie, changing it from “Max Brown” to “Jen Brown”.

To delete a cookie, you can simply provide an expiration date that occurred in the past. When the browser sees that the cookie has expired, it will delete the cookie automatically.

Fun fact: the formal Unix time count began on Thursday, January 1st 1970 at midnight GMT. This is known as the “Epoch” time. Timestamps in integers are similarly also known as “milliseconds since epoch”, or the number of milliseconds that have taken place since January 1st 1970.

To easily delete any cookie, simply set its expiration date as the epoch timestamp:

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";

This statement will delete a cookie named “username” if one exists.

Some browsers will not allow the deletion of a cookie if the path is not specified. Therefore, it is important to always specify the path when working with cookies.

Get cookies

Getting all cookies is very simple. Cookies are stored as a set of strings separated by semicolons. You can access this value by calling document.cookie as seen in the example below:

document.cookie = "username=Debra White; path=/";

document.cookie = "userId=wjgye264s; path=/";

let cookies = document.cookie;

console.log(cookies); // expected output: username=Debra White; userId=wjgye264s

The above code sets two cookies – username and userId, and returns the cookie values to the variable cookies as a single semicolon-delimited string. Note that the return value does not include the specified path.

Retrieving the value of a single cookie requires a little bit of legwork.

First, we’ll write a function that can determine the value of a cookie when given the cookie’s name. Here is our sample code:

function getCookie(cName) {

const name = cName + "=";

const cDecoded = decodeURIComponent(document.cookie); //to be careful

const cArr = cDecoded .split('; ');

let res;

cArr.forEach(val => {

if (val.indexOf(name) === 0) res = val.substring(name.length);

})

return res;

}

Exploring function getCookie() by line

The function getCookie takes a cookie’s name as a parameter, then performs the following steps:

  1. The first line assigns the requested cookie name to a const variable name. It appends an equals sign to the end of the name. For example, passing in a cookie value ‘username’ will result in ‘username=’ being stored in the name variable.
  2. The next line retrieves all of the cookies using document.cookie, then applies decodeURIComponent() to the result. This function “cleans” the string from “encoding traces” that may have been included in the cookie content. You have likely seen these encoding traces before, they look similar to this: %20%24username%20.
  3. As explained in the previous section, document.cookie returns results as a string containing all cookie values separated by semicolons (;). Here I have used the split() method, asking it to split the string’s values apart when it encounters a semicolon followed by a blank space. The result will be an array of cookie strings.
  4. The following two lines define the return variable, res, and call the forEach() method on the array of cookies obtained in line 4 (cArr). The forEach() iterates through an array, executing a callback function once for each array element. In the above example, if the value stored in variable name appears at the beginning of the string (i.e. at index 0), the inner block assigns the content of the cookie (i.e. the value after the “=” sign) to the variable res. The value length is larger than index by one. This allows us to trim off both the full string name of the cookie, and the trailing equality sign by starting the trim at index = name.length. For trimming I used the substring() method, which produces a substring of the specified length from the original input string.
  5. If the forEach() method was not able to find the requested cookie, the value ‘undefined’ will be returned.

Keep in mind that in many cases, working with cookies will begin with fetching a cookie’s value, and then requesting information from the user if the requested cookie is not found.

Related Articles:

JavaScript – How to Use The Array forEach() Method

JavaScript – How to Use the String length Property

JavaScript – How to Get an Input’s Value

https://iq.opengenus.org/third-party-cookies/

Third part cookies are cookies set by external websites which we do not visit directly. A widespread use of such an external site can result in tracking and other implications. In this article, you will learn:

  • What are third party cookies and how it works?
  • Cookie profiling, its concern and comparison of thrid party cookie with first party cookie
  • A demonstration to build your own page with a third party cookie
What are Third Party Cookies?

When a user visists a website, that particular website may leave some cookies on the user's local machine to identify it later. These are known as first-party cookies. These websites often load ads from third party servers. These third-party servers also place some cookies on the user's machine. These cookies which are placed by third-party domains are known as third-party cookies. These originate from a different domain than the one the user is visiting.

How Third Party Cookies Work?

The key way of setting a third party cookie is to set a cookie by a JavaScript code which is coming from a different server than the server you are directly visiting. This happens because websites do refer to external JavaScript files for various reasons such as:

  • Better caching (Content Delivery Network) (consider JQuery)
  • Serving an external service (like sharing buttons) on the web page
  • Serving JS files through external server transfers the responsibility of maintainence on a different team

and so on.

For instance:

  1. Let there be a website site.com, which loads a banner from ad.com like so:
<img src ="https://ad.com/banner.jpg">


HTML

  1. Along with the banner, the server at ad.com may Set-Cookie header, or use a cookie-parser, with a cookie like id=5678. Such a cookie originates from ad.com and is visible to only ad.com.
  2. The next time ad.com is accessed, it gets the cookie id=5678 along with it, helping it recognise the user.
  3. The important point to remember is, if the user visits another site, another.com, which also has banners from ad.com, the server at ad.com will recieve the cookie and recognise the user, thus tracking the him/her as he moves between sites.

thirdparty

Note: If a script sets a cookie, then no matter where the script came from, it belongs to the domain of the current webpage.

Cookie profiling, also known as Web Profiling, is a technique used to track a user's overall activities online, by making use of persistent or permanent cookies. This kind of profiling is usually done by marketers, or advertisers who collect and collate cookie information, to create a single "profile" of a user. This helps them in targetting potential customers based on their browsing habits. This is the reason most of the sites have advertisements on their pages.

A common example would be seeing the advertisement of the particular shirt you were thinking of buying from that famous online retailer pop up on a separate website altogther.

Famous, and big advertisers buy advertisement rights over thousands of popular sites, and place permanent cookies on the users local machine. These cookies are identified on other websites as well where the same advertiser has more ads, thus showing ads based on your browsing history, age, gender, etc.

The cookies placed are third-party cookies, since these are placed not by the domain you are visiting, but by another domain whose ads are being hosted by that particular website.

Third Party vs First Party Cookies
  • Reading and Setting Cookies: First-party cookies can be set by publisher's web server or by any JavaScript loaded on the website. Third-party cookies can be set by a third-party server via code loaded on publisher's website.
  • Availability: First party cookies are only accessible via the domain that created it. Third party cookies are accessible on any websites that load the third-party code.
  • Browser Support, Blocking, Deletion: First-party cookies are supported by all browsers. These can be deleted, but generally not done to improve user experience. Third-party cookies are supported by all browsers, but many block them by default. Most of the users also delete them on a regular basis.

Cookie profiling is an advantage for marketers as it helps them target potential customers more accurately. The more users they target based on their past habits, the more chances are of their products being sold.
However, if used maliciously, this may become a breach of privacy, and even play a role in cyber bullying.

Some websites sell these profiles for extra profit. This leads to a breach of privacy. This data may also be used to stalk certain individuals and terrorise them.
In recent times Facebook has faced severe backlash due to its privacy policies. It tracks not only logged-in users, but also logged-out users, and even non-members. It inserts cookies to your machine, when you visit the sign in page, even when you don't log in, and also work together with ir's social plug-ins, popularly known as "Like" and "Share" buttons.

While some people don't care about this profiling much, a majority of users do not like the idea of certain websites "following" them around.

For example, here are the third party cookies loaded by a common domain www.staticxx.facebook.com on:

  • Wattpad.com
  • Zomato.com

These can be viewed in the Chrome Developer Tools

See for Zomato:

Screenshot--926-

See for Wattpad:

Screenshot--927-

To try sending third-party cookies, set up a NodeJS server install cookie-parser, and use as:

response.cookie('<cookie-name','<value>',{<options>});


Js

Access the cookies normally from the client side using:

document.cookie


Js

Here's an example to show the basic implementation of third-party cookies, using Express and NodeJs for backend.

Demonstration of third party cookies

add.js will have the code for setting up placing third-party cookies. It will send the banner.png file to any server which requests it by using the route /banner

add.js:

const express = require('express');
const app = express();
const port = 8000;
var path = require('path');
var cookieParser = require('cookie-parser');

app.use(cookieParser());
//set cookie as number of hits
var hits = 0;

app.get('/', (req, res) => res.send('Hello World!'))

//on getting a GET request, a cookie will be set if it does not exist yet, otherwise it will be logged
app.get('/banner', function (req, res) {
    hits++;
    if (!req.cookies.hasOwnProperty("third-party")){
        res.cookie("third-party", hits.toString(), { maxAge: 9999999 });
    }
    else{
        console.log(req.cookies);
    }
    res.sendFile(path.join(__dirname + "/banner.png"));
});

app.listen(port, () => console.log(`Example app listening on port ${port}!`))


JavaScript

site.js will have the code for a regular website which will send a GET request for the banner from ad.js. In addition, it will place its own cookies on the visiting user.

site.js:

const express = require('express');
const app = express();
const port = 3000;
var path = require('path');
var cookieParser = require('cookie-parser');

app.use(cookieParser());

//serves homeSite.html and sets first-party cookie
app.get('/',function(req,res){
    res.cookie("first-party","785");
    res.sendFile(path.join(__dirname+"/homeSite.html"));
});

app.listen(port, () => console.log(`Example app listening on port ${port}!`))


JavaScript

homeSite.html will be the page served by site.js. It will access the cookies placed by the server with embedded JavaScript using document.cookie.

homeSite.html:

<!DOCTYPE html>
<head>
    <script>
        function getCookie() {
            document.getElementById("cookie").innerText = document.cookie;
        }
    </script>
</head>
<body onload="getCookie()">
    <img src="http://localhost:8000/banner">
    Cookie:<p id = "cookie"> </p>
</body>
</html>


HTML

When ad.js gets the first GET request from site.js, it places a cookie on it, which is reflected on homeSite.html page:

[Screenshot--933-

The second time it gets another request site.js, ad.js logs the value of the cookies to the console:

Screenshot--935-

This example would have given you the knowledge to build your own third party cookies.

Cookies Ultimate Guide

https://html.com/resources/cookies-ultimate-guide/

Cookies, or, to give them their formal name, HTTP cookies, are text files made up of tiny bits of data, which are stored on a web browser. These tiny bits of data are used by websites to track a user’s journey, enabling them to offer features that are specific to each individual user. Because of this, cookies are at the heart of a website’s functionality. For example, they can be used for shopping carts on e-commerce sites.

On the one hand, cookies are integral to the way the internet works, but they’re also a cause for concern when it comes to security and privacy risks. However, by understanding how cookies work, both day-to-day users and developers can protect themselves from the negative aspects of these tiny bits of data.

With this in mind, this guide provides an in-depth overview to cookies. It has been broken down into two usable parts:

  • Understanding Cookies — A Layman’s Guide: all of the basics you need to know as an everyday internet user.
  • Understanding Cookies — A Developer’s Guide: a more in-depth look at how cookies work, with advice on how to use cookies while adhering to the laws in place. It then concludes with some technical resources for those who want to go even further into the world of cookies.

Contents [hide]

Understanding Cookies — A Layman’s Guide

Having a basic understanding of HTTP cookies is essential for every internet user, regardless of whether you’re just using it for personal use or you’re a web developer who’s making a living from it. These basics include what purpose cookies serve, and what security and privacy risks they pose. However, to give you a better overview, we thought it was worth delving into the history of cookies and where they came from, so here goes!

The History of Cookies

In 1994, Lou Montulli developed cookies for the first time. As a Netscape Communications employee, Montulli worked alongside John Giannandrea to develop cookies into a unique solution that would help make shopping carts for e-commerce stores possible. This means the first primary usage of cookies on the internet was to establish whether a visitor coming to Netscape’s website had already visited it or not.

At the start, all supported browsers accepted cookies by default, which meant hardly any end users were aware of their use or presence. However, in February 1996, this changed, when their use, purpose, and existence were revealed in a piece published by The Financial Times. Over the next few years, the media placed cookies under intense scrutiny due to the privacy risks created as they tracked visitors across a website.

This resulted in the internet Engineering Task Force (IETF) being tasked with establishing a formal cookie specification. Agreeing with the media’s concerns, particularly with the risks involved in third-party cookies (AKA: tracking cookies), the IETF tried to make it a requirement that all third-party cookies were disallowed, or, they were only allowed once a user had explicitly opted into them.

However, the industry-leading browser developers (eg, Microsoft and Netscape) didn’t follow these recommendations and continued to allow tracking cookies from third-parties, such as online advertisers.

Today, even though the IETF’s cookie specification acknowledges the use of tracking cookies and the risks they poses, it places much of the responsibility of managing this risk onto browser developers, “This document grants user agents [browsers] wide latitude to experiment with third-party cookie policies that balance the privacy and compatibility needs of their users.”

However, there are other legalities that have come into play with regards to cookies. We’ll take a look at these later on in the guide.

For each specific user, there will be bits of data that are associated with them by cookies. For example, when you go to a website, you may be identified as “User X” by a cookie that’s been delivered by the site. Therefore, if you leave the site but return to it later, the cookie you’ve been given will be used by the site to identify you as “User X” who’s been on the website before.

At a minimum, cookies contain two bits of data: an identifier for a unique user and some information about this user. However, they can also contain a whole host of attributes that inform browsers what they should do with the cookie — something we’ll touch on in the developer-targeted part of this guide.

A common working example of this is what’s known as an authentication cookie. For example, when you log into a site, a cookie may be returned that identifies your account, confirming you’ve successfully logged in. Then, when you interact with this website in the future, this cookie will act as confirmation that you’re a user who’s logged into the site.

Different Types of Cookies

There are a number of different ways cookies can be grouped together, and below we’ll look at the four most common. This should hopefully add to your understanding of how they are used as well as how they work.

Session Cookies

These cookies are temporary and will only be stored in the memory of your browser while it’s open. When it’s closed, the cookie will be removed from your browser’s history, and, because of this, they are a lower security risk. You’ll often find these cookies working within e-commerce shopping carts, controlling what a user sees on a page when they’re conducting a one-off, multi-page site visit, or for other storage means that are short-term.

Persistent Cookies

These cookies are used over a much longer period of time, as an expiration date is tagged to them by the issuer. This means, even when your browser is closed, the cookie will be stored on it. And each time you return to the website that created this cookie, or you go to a website that has a resource produced by the cookie’s issuer (eg, an ad), this data is returned to the issuer.

Persistent cookies, can, therefore, track your browsing activity not just on the original site where the cookie was created but on other sites that have a resource which has been produced by the original site. For example, Facebook and Google use these kinds of mechanisms to create a user activity log across a range of different websites. So, when you click “Remember Me” (or something similar) after you’ve logged into your online account somewhere, you’ll be creating a persistent cookie, which will store your login details on your browser.

As these persistent cookies are present for a longer period than session cookies, and can essentially track what you’re doing over more than one site, a greater security risk is posed by them.

First-Party Cookies

Created by a site you’re visiting, first-party cookies help a website carry out a number of purposes, such as allowing you to add more than one item to your online order. If you disabled first-party cookies, every time you added an item to your shopping cart it would be treated as a new order as you’d be unable to purchase more than one item in one transaction.

Third-Party Cookies

Created by a site you’re not currently visiting, third-party cookies are most commonly used to track a user who’s clicked on an ad, associating them with the domain that’s referred them. For example, if you’re on a website and you click on an advertisement, a third-party cookie is generated to associate your traffic with the website where the advertisement was shown.

Even though cookies do play a very important role in our browsing activities, there are a number of threats posed by these, especially when it comes to the invasion of privacy and the security of websites that are using them.

The Risks of Cookies and What You Need to Watch out For

When you’re using the web, you’ll want to know what risks are presented to you by cookies, how you can view them, and how to delete them, if necessary. To start with, we’ll look at the risks involved with cookies, which can be placed into two categories — fraud and the invasion of one’s privacy.

Although quite complex, it’s worth familiarizing yourself with cookie fraud in case you come across a site that’s exploiting users through this method.

In a lot of cases, cookie fraud will either be a malicious website attacking another website by using legitimate uses as a proxy, or a legitimate user’s activity being tagged with a false session ID for game tracking systems.

Here are four common types of cookie fraud and what they involve:

Cross-Site Scripting (XSS)

Here, a user will receive a cookie after they’ve visited a malicious website. This cookie contains a script payload that targets another website, but the malicious cookie is in disguise and looks as though it’s come from the website that’s being targeted. Therefore, when a user visits the targeted site, this fraudulent cookie (and its script payload) is sent to the targeted site’s server.

This type of vulnerability may be used by attackers to get past certain access controls like the same-origin policy.

Session Fixation

When this occurs, a user will be given a malicious cookie that contains the session ID of the cookie’s issuer. Then, when the innocent user goes to log into a domain that’s being targeted, the user’s session ID isn’t logged but the cookie issuer’s is. This makes it look as though the issuer is performing certain actions on the targeted domain but it’s the user that’s actually performing them.

This type of cookie fraud allows attackers to take over valid user sessions.

Cross-Site Request Forgery Attack (CSRF)

A legitimate cookie is received by a user when they visit a legitimate site. However, they then visit a malicious site which instructs the browser of the user to perform an action that targets the legitimate site they’ve previously visited. A request is received by the legitimate site alongside the legitimate cookie, and the same action is performed as it seems to have been triggered by the legitimate user, but it hasn’t, it’s been initiated by the malicious site.

In a cookie tossing attack, a user is provided with a cookie by a malicious site, which has been designed to look like it’s come from the targeted site’s subdomain. For example: http://subdomain.placeholder.com. Therefore, when the user goes to the targeted site (placeholder.com), all of the cookies are sent, including legitimate ones and the subdomain cookie. Where the cookie that’s interpreted first is the subdomain, this data will overrule any of the legitimate data contained in the other valid cookies.

The above examples demonstrate that, in most cases of cookie fraud, the cookies are being used to perform malicious actions using the legitimate user’s identity, or to falsify a legitimate user’s identity.

The first important thing to note is cookies aren’t viruses, even if they’re malicious. They cannot execute actions on your computer because they’re made up of plain text, which means you aren’t protected against malicious cookies through your antivirus software. Instead, there are a couple of things you can do to prevent yourself from becoming the next cookie fraud victim:

  • Make sure your browser is updated: a lot of the cookie exploits carried out are designed to make use of an outdated browser’s security holes. Today, a lot of browsers update automatically. But if you are using a browser that’s out of date, you should update it straight away.
  • Avoid any sites you’re not sure about: if you ever receive a warning about a site, whether it’s from a search engine or your browser, don’t go onto the site.

Invasion of Privacy

Even though cookie fraud is a concern for many people, the greater worry is the risk posed by the invasion of privacy. When you think about how many websites have a Google resource embedded in them (eg, Google Maps, Analytics, or Adsense), it isn’t hard to work out how Google is constantly adding to its huge record of web users’ cross-site activity. In fact, a lot of users feel as though the use of the information by Google to provide targeted ads is a tad creepy, to say the least. But more worrying still is the potential invasion of privacy that’s occurring.

It isn’t just Google, of course. Many other web advertising platforms, such as Facebook, Disqus, Revcontent, and Infolinks, are trying to improve user targeting and the delivery of relevant ads by mining more and more data about each and every user.

Therefore, if you’re going to use the internet, and you’re going to let your browser accept cookies, your every move is being tracked.

Protecting Your Online Privacy

Unfortunately, there isn’t a clear-cut way around accepting cookies. But, there are a number of things you can do which limit how much time your privacy is invaded by cookies:

  • Look at your browser’s privacy and security settings: firstly, open up the settings menu for your browser and find the privacy and security section. Here, you’ll be able to alter your browser’s cookie policies. You can be as severe as you wish. At the same time, you don’t want to make it too difficult to access certain features on different websites.
  • Use an “Incognito” or “Private” browsing mode: the majority of modern browsers offer you the chance to browse the internet without any cookies. Therefore, when you’re surfing the web, none of your existing persistent cookies will be used, and any persistent cookies created during your time online will be deleted when you close the browser. However, it’s worth bearing in mind that none of your passwords will be saved in this mode. And each time you visit a site it’ll record it as your first ever visit, so you might not be able to see your “favorites” or features such as “recommended for you.”
Viewing and Deleting Your Browser’s Stored Cookies

The process of viewing and deleting the cookies stored by your browser is relatively easy, especially with most modern browsers. Even though this can vary with each browser, you’ll generally need to enter the privacy and security section of your browser’s settings.

Here, you should be able to locate an option which allows you to see the cookies that have been stored. As you view each of these individual cookies, you’ll be given the chance to delete any of the ones you want to permanently remove from your browser, as well as an option to delete them all if you want.

If you do get stuck trying to do this, Google has the answer to everything — simply type in “How to view cookies in [INSERT BROWSER HERE].”

Zombie Cookies

Pay close attention to zombie cookies, as these are cookies that cannot be deleted through your browser’s settings. They’re automatically recreated every time you delete them by a script that’s stored outside the memory of your browser. So, this cookie will be like a bad smell and will continue to reappear. However, this doesn’t necessarily mean they’re a malicious form of cookie; they have legitimate uses. But, because of this strange, undeletable, and somewhat questionable behavior, many privacy advocates, and security experts do disapprove of them.

If you do want to delete a zombie cookie, you’ll need a little more patience, perseverance, and savvy Googling skills, as you’ll need to find other like-minded individuals who’ve managed to get rid of this undeletable cookie. Essentially, you’ll have to work out where the cookie-recreating script is stored so you can delete this script and prevent this zombie cookie from being reborn time and time again.

Controlling Cookies Through Browsers and Devices

Thankfully, you’re online privacy and security isn’t just in the hands of web developers. You can still manage your browser’s cookie policy. All it takes is a little time to work out what cookie policy you need to reduce the risks you’re presented with when using the internet.

As we’ve already seen, managing cookies can be different depending on the browser you’re using, but we’ll show you how to manage your cookie policy through the most popular desktop browsers: Chrome, Firefox, Microsoft Edge, and Internet Explorer.

Controlling Cookies in Chrome
  1. Open your settings through the main menu, then scroll to the bottom and click “Show advanced settings…”

  2. Select “Content settings.” As a default, you’ll find the Allow local data to be set (recommended) setting has been preselected for you. This means all first- and third-party cookies are being accepted by Chrome.

  3. If you want to change this policy, there are other options you can choose from, which are:

    1. Keep local data only until you quit your browser: if you want to be able to accept cookies while you’re using the internet but want them deleting as soon as you close your browser, select this option.
    2. Block sites from setting any data: if you want to disable all cookies, select this option.
    3. Block third-party cookies and site data: if you don’t want to accept third-party cookies, select this option.
    4. Manage exception: if you want to manage the sites that have a site-specific cookie policy, click this button to be taken to a list of these websites.
Controlling Cookies in Firefox
  1. Open the “Options” section of your Firefox browser menu and then select the “Privacy” tab.

  2. In the section labeled “History,” you’ll find a drop-down menu where you can click “Use custom settings history.” This will then allow you to select from a number of options, which are:

    1. To disable all cookies, deselect the option Accept cookies from site as this will have been pre-selected as default.
    2. To block all third-party cookies, or to accept all third-party cookies (from sites you’ve visited before), you can deselect or select the option Accept third-party cookies.
    3. To manage websites who’s cookie policy is different from Firefox’s policy, click the Exceptions button.
    4. To choose how long you keep cookies for (eg, until you close the browser or the cookies expire), opt for the Keep until option.
Controlling Cookies in Microsoft Edge
  1. In the settings menu of the browser, click on “View advanced settings” which you’ll find at the bottom of the page.

  2. At the bottom of the next page you’ll find a drop-down menu for cookies, which presents you with three straightforward options, which are:

    1. Don’t block cookies (this will have been preselected by default)
    2. Block all cookies
    3. Block only third-party cookies.

The savvy among you will notice there isn’t the option to delete all cookies when you close Microsoft Edge. However, you are able to do this if you go back into the primary settings menu. At the top of the “Advanced Settings” menu you’ll notice a « button — click on this.

Next, you’ll need to choose the button that says “Choose what to clear”, which is located just below the “Clear browsing data” option. Click the option Cookies and saved website data, before selecting the option that says Always clear this when I close the browser.

Controlling Cookies in Internet Explorer

It doesn’t matter whether you’re using IE 9, 10, or 11, because cookies are all handled in the same way.

  1. Start by opening the “Internet Options” menu before selecting the “Privacy” tab and then the “Advanced” option.
  2. From this next menu you’ll be able to establish what policy you want in place for first- and third-party cookies. You can also override the current cookie policy or you can select Always allow session cookies.
  3. If you want to be able to delete cookies each time Internet Explorer is closed, you’ll just need to return to the “General” tab, before selecting the option — Delete browsing history on exit.
  4. To save and apply these changes, you’ll need to click “Apply,” which is at the bottom of the menu.
Controlling Cookies on Mobile Devices

As a native browser is included with most mobile operating systems, the process of managing cookies on mobile devices can be entirely different to that of desktop browsers. Furthermore, the mobile version of a desktop browser may not present you with as many options, which can create further complications.

To help you along the way, here’s how you can manage cookies on iOS, Android, and Blackberry mobile devices:

Controlling Cookies on an Apple iOS Device
  1. If on iOS you use Safari, you can use the “Settings” app to manage your cookie policies.

  2. Simply scroll down to select “Safari.” Once in this section, you’ll need to scroll down to the option “Block cookies.” Here, you’ll be presented with four options, which are:

    1. Always Block
    2. Allow from Current Website Only (these are first-party cookies)
    3. Allow from Websites I Visit (this allows a limited number of third-party cookies and is the default option)
    4. Always Allow.

However, if you’re using Chrome, you won’t be able to manage the cookie policy. You will, however, be able to delete them. To delete the cookies on Chrome, you’ll need to open the app and select the “Settings” option from the menu. Scroll down to “Privacy” and then to “Clear Browsing Data.” Here you can select what it is that you want to delete, so make sure you select “Site Data” and “Cookies” before selecting to “Clear Browsing Data.”

Regardless of whether you’re using Chrome or Safari, you will be given the option to browse “Incognito” or “Privately”, respectively. Simply open up a new tab using these options, making sure you close this tab when you’ve done so no cookies are stored after your browsing session has finished.

Controlling Cookies on an Android Device

A built-in browser is standard with most Android devices, however, these browsers can vary with each phone model and manufacturer. Therefore, how you manage the cookies in these browsers can vary quite a lot.

In general, you’ll need to open up the browser, and the browser’s settings menu, before locating the privacy settings. If your phone is using Chrome, you’ll be able to manage your cookie policy with ease. All you need to do is go to the menu and find “Settings”, navigating yourself to “Site Settings” before selecting “Cookies.” Here, you’ll be able to turn on or off your acceptance of cookies, deciding whether you want to Allow third-party cookies or not, while also managing the websites that are exempt from Chrome’s cookie policy.

Controlling Cookies on a Blackberry Device

You will find some of the more recent Blackberry devices are run by Android, which means managing cookies on these phones can be done using the procedure discussed in the Android section above. However, if your device is running Blackberry 10, you’ll need to do the following:

  1. Run the browser and go to its menu
  2. Choose “Settings” before clicking “Privacy and Security”
  3. Here, you’ll be able to choose whether you want to accept cookies or not, clear all cookies, and manage the exceptions of certain websites.

Understanding Cookies — A Developer’s Guide

As cookies are only text files, many wrongly believe they’ll be easy to deal with. But that’s not true.

Depending on the server that’s issuing the cookie or the cookie’s overall purpose, cookies can be used in a variety of different ways. In this section of our in-depth guide, we’ll discuss (briefly) how you can implement cookies, before delving into the legalities involved with using them.

Finally, we’ll finish with a number of resources that provide even more information on implementing cookies, and how you can utilize these in your web development role.

Implementing Cookies on a Technical Level

A cookie is created when a browser is told to create one by a web server. These instructions are normally sent in a HTTP header, looking a bit like this:

Set-Cookie: <cookie_name>=<cookie_value>

The document.cookie method through client-side JavaScript can also be used to create cookies.

Then, once a browser has created a cookie, when any requests are made by the browser for the same domain, any cookies that belong to this domain will be sent back as part of the request.

In the example above, you’ll find a “session cookie.” But you can create persistent cookies by adding the attribute “Expires” into the Set-Cookie header. You may also want to add a number of other attributes which will help you to control how cookies are treated by browsers. These include:

  • A “Secure” attribute: this tag for cookies will only be sent if the browser’s request is sent through an encrypted protocol (https).
  • A “HttpOnly” attribute: when a cookie is flagged with this attribute, it won’t be accessible to JavaScript in the webpage’s Document Object Model (DOM), and will only be transmitted back to the domain that issued it.
  • A “SameSite” attribute: this attribute makes sure cookies are only transmitted back to their originating website. The use of these cookies is relatively new.

Being aware of the directives and privacy laws involved in cookies is crucial when you’re a web developer. Ignoring the laws involved in the application of cookies could result in a steep fine, or worse.

So, when you start using cookies, here are three legal issues you’ll need to take note of first:

Even though this started out as a directive, every country in the EU has now had to incorporate this into law. This law states that, if your website is targeting consumers in an EU country or your business is based in the EU, you must get permission from a user before you use cookies.

FTC Disclosure Requirements

Two of the primary uses of cookies are for affiliate sales and advertising through third-party tracking. However, if you’re using cookies with this in mind, the FTC states that you must make visitors aware of what you’re doing.

Privacy Policy Documents

In several countries, including the US, Australia, UK, and every country in the EU, you must let a user know what you’re using their personal data for. So, if you’re using a cookie to track their activity (eg, Google Analytics), you’re legally required to publish a privacy policy which explains what data you’re collecting and how you’re using it.

It’s not hard to comply with the laws in place for cookies, and, in most cases, you’ll only need to do the following:

  • If you’re targeting consumers in the EU or you’re based in the EU, be sure to make users aware that your site is using cookies and they accept this.
  • If you have affiliate ads placed on your site or you’re allowing paid advertisements, make sure there’s an obvious disclosure on your site that shows this information.
  • If you’re collecting any user data or you’re tracking users’ activity, include a detailed privacy policy on your website that shows what data you’re using and how it’s being used.

Complying with these three guidelines will help you to stick to the various laws that are in place. However, this isn’t legal advice, so if you do have any questions about the legal implications of cookies, you should seek professional advice from a specialist lawyer.

Resources

As promised, here’s an extensive list of resources that help you choose how you’re going to use cookies on your website. These websites and tutorials will help you decipher what information you need to create the cookies on your application or website:

Conclusion

It’s obvious cookies are integral to the internet, but along with their benefits there are also disadvantages. Even though they provide a website with features that are business critical, they also present users with a number of privacy and security issues.

However, it’s clear cookies aren’t going to be going anywhere soon because most websites are using them in one way or another. Therefore, educating yourself on how cookies work and how you can protect yourself from cookie fraud and invasion of your privacy, you can be better prepared to take advantage of them without putting yourself at any risk.

 

Read more: https://html.com/resources/cookies-ultimate-guide/#ixzz7IfaixFBv

Scroll to Top