How to use JavaScript to set cookies for a specific page only?

JavascriptWeb DevelopmentFront End Technology

We can set cookies for a specific page only using JavaScript. We use the path attribute of the document.cookie property to set the cookie on a specific webpage. Cookies are small text files (4 KB) that store important information such as username, email, session id, and other preferences that help customize the webpage for a particular user.

Something so trivial as this is a user preference and thus can be conveniently stored in a corresponding cookie file.

The pathname property of the Window location returns a string containing the path of the current webpage. The path is basic information about where the current webpage is stored on the server.

document.cookie

The document.cookie property returns a list of name/value pairs separated by (;). It stores information about the cookies related to the current webpage. We can set cookies by providing name/value pair. We use the path attribute of the document.cookie property to set the cookie on a specific webpage.

Syntax

document.cookie = "name = yourName; path = yourPath";

Where “yourPath” is the path to the specific page on which you want to set the cookie.

Let’s look at an example to understand better.

Example 1

In the code snippet below, we validate as well as extract the value entered by the user and create a cookie using the name/value pair on the current webpage.

<html> <head> </head> <body> Set cookie on a specific page ! <form name="myform" action=""> Enter name: <input type="text" name="customer" /> <input type="button" value="Set Cookie" onclick="WriteCookie();" /> </form> <div id = "result"></div> <script> function WriteCookie() { // user input validation if (document.myform.customer.value == "") { document.getElementById("result").innerHTML = "Enter some value!"; return; } cookievalue = encodeURIComponent(document.myform.customer.value) + ";"; var myPath = window.location.pathname; document.cookie = "name=" + cookievalue + "path=myPath"; document.getElementById("result").innerHTML = "Setting Cookies : " + "name=" + cookievalue; } </script> </body> </html>

The input from the user is collected, validated, and then used to create the cookie. We use the encodeURIComponent to convert the value entered from the user and convert it in form of a resource identifier string. Since the cookies are sent as HTTP headers, it is a good practice to encode the values of cookies before creating them. This ensures that the values follow the HTTP standard by replacing certain characters with escape characters.

Note however that document.cookies does not return all the cookies associated with a webpage. With a server side language like JavaScript, we have the limitation that Secure same-site connections only cookies are sent with a HttpOnly flag and thus not visible to JavaScript.

For example, in the above code, we only get the _fbp cookie but not the other cookies related to sessionId.

If we examine the cookies for a site by clicking on the small lock icon that is prior to the URL in the search bar. We can access all the cookies related to the site.


Notice that there are 3 cookies associated with the site but document.cookie shows only one which is accessible to JavaScript.

We can set the cookie to be accessible to all the web pages. This can be done by setting the path attribute to “/”. Apart from that, we can use the expires attribute to set the time validity of the cookie.

Example 2

In the below code snippet, we take the name-value pair from the user and set a corresponding cookie in the document object.

<!DOCTYPE html> <html> <body> <p>Enter a Name-value pair: </p> <input id = "cookie" type = "text">{name=value} <br> <p>Click the below button to create a new cookie. </p> <button id = "button" onclick = "create()"> Create ! </button> <br> <p id = "alert"> </p> Click below to show all cookies ! <button id = "show" onclick = "show()"> show cookies ! </button> <div id = "result"></div> <script> var result = document.getElementById("result"); function create(){ var cookieObj = document.getElementById("cookie"); if (cookieObj.value.length == 0){ alert("Please Enter name-value pair") } else{ var value = cookieObj.value document.cookie = value ; document.getElementById("alert").innerHTML = "cookie created !"; } } function show(){ var val = document.cookie; result.innerHTML = "Name/ Value pair of Cookies: " + val; } </script> </body> </html>

The "create !" button triggers the create() JavaScript function which then creates a new cookie. The show button can then be used to see the newly added cookie to the webpage.

Conclusion

Cookie is an innovative trick to enhance the user experience by storing small pieces of details about the user. However, they are also used in many malicious attacks and thus should be handled with care.

raja
Updated on 21-Sep-2022 07:55:00

Advertisements