Do cookies stored with the document.cookie method specific to the current webpage?

I have been working with cookies in my asp.net web application using JavaScript to store various values. I am currently using document.cookie to save these values as a lengthy string. However, I am encountering an issue where the value I save in the cookie is only accessible within the current page URL.

For example, if I save a value in a cookie on http://myapp/doc1.aspx, I am unable to retrieve it on http://myapp/doc2.aspx.

Is the scope of document.cookie limited to a single page? How can I ensure that cookies can be saved and read across all pages on the site?

Update

Below is my current code for getting and setting cookies:

function getCookie(c_name)
{
try{
  if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    {
    c_start=c_start + c_name.length+1;
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    }
  }
  }
  catch(e)
  {}
return "";
}

function setCookie ( name, value, exp_d) 
{
  var cookie_string = name + "=" + escape ( value );

  if ( exp_d )
  {
    var exdate=new Date();
    var expires = new Date ( exdate.getYear(), exdate.getMonth(), exdate.getDay()+exp_d );
    cookie_string += "; expires=" + expires.toGMTString();
  }

  document.cookie = cookie_string;
}

However, I am experiencing issues with the values of the cookies being different on various pages. Any insights or suggestions would be greatly appreciated.

Thank you.

Answer №1

Cookies come with a domain and a path. Typically, the domain is set to where it originates from and the path is set to the root, but you can customize these settings:

Imagine a resource at that creates a cookie, either from the server or through client-side JavaScript.

By default, the cookie's domain is www.example.net and the path is /. This means it's visible to any resources with a URI matching ://www.example.net/ where * acts as a simple wildcard.

You can change the domain to example.net, but not to example.org - it must be a subdomain. (There are some special and imperfect rules to prevent setting a cookie for a top-level domain like .net)

The path can be set to /foo/bar/baz, /foo/bar, or even /foo/ba as it uses simple substring matching. For example, if it's set to /foo/bar/, it will be visible to a resource at but not at

Additionally, there is a secure property that restricts the cookie to the HTTPS protocol.


For more information on setting these properties, visit http://www.quirksmode.org/js/cookies.html.

Answer №2

To resolve the problem, simply include the following syntax:

add ";path=/;" to the end when storing the cookies, like this:

document.cookie = cookie_name + "=" + savedData + ";path=/";

Answer №3

Cookie policies are applicable across the entirety of the domain. The cookies generated by the provided code will be accessible to all pages residing on your domain.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to update the state of an array within a .then() function in React?

` After retrieving an array of points with city and state information, I attempted to convert these points to latitude and longitude by making a fetch call. However, upon trying to update the state of the newly generated array, I found that it remained ...

Transforming JSON data into a hierarchical tree structure in JSON format

I have a JSON treeData that I need to convert into a different format so that I can use a visualization library in JavaScript. treeData={ "leftNode": { "leftNode": { "leftNode": { "leftNode": { ...

Decide whether an angular rotation is within the camera's field of vision inside a spherical object

Seeking assistance with a three.js project. I have set up a camera inside a SphereGeometry at position (0,0,0) and am projecting an image on the sphere's wall. My goal is to create interactive JS elements outside of the threejs framework that respond ...

What is the process for incorporating a Bootstrap link into a specific ReactJS file?

In my current project using React JS, I found the need to incorporate Bootstrap in certain pages. To do this, I initially placed the following code snippet in the Public folder within index.html: <link rel="stylesheet" href="https://netdna.bootstrapc ...

`Gradient blending in ChartJS`

Currently, I am facing an issue with my line chart having 2 datasets filled with gradients that overlap, causing a significant color change in the 'bottom' dataset. Check out my Codepen for reference: https://codepen.io/SimeriaIonut/pen/ydjdLz ...

Problem with Java class in GWT JsInterop

Having some trouble with JsInterop while wrapping up a piece of JavaScript code. The JavaScript code looks like this: com = { gwidgets: {} }; com.gwidgets.Spring = function () { this.name = "hello"; }; com.gwidgets.Spring.prototype.getName = ...

What is the best way to prevent images from being loaded with broken links?

Currently, I am working on a new feature that involves rendering images from servers. In the process of aligning these images, I noticed an excessive amount of white space due to loading images with broken links. https://i.stack.imgur.com/jO8BR.png Here ...

Encountered an error when attempting to use the 'removeChild' function on a node that is not a child of the specified node. This issue arose while interacting with an input box

I recently created a todo app with a delete functionality. However, after deleting an element successfully, I encountered an error when typing in the input box stating: Failed to execute 'removeChild' on 'Node': The node to be removed i ...

"Using jQuery's animate() function to dynamically change text content

I'm currently venturing into the world of jQuery animate() and decided to create a presentation-style project for practice. However, I've hit a roadblock when attempting to alter the text within my div element in the midst of an animation utilizi ...

Troubleshooting a LESS compiling issue with my Jade layout in ExpressJS

Implementing LESS compilation on the server side using Express was successful, but I faced an issue with jade not recognizing less in layout. Error message displayed in my terminal: if(err) throw err; ^ Error: ENOENT, open '/Users/li ...

Managing a digital timepiece within a multiplayer gaming environment

I'm currently developing a fast-paced game where players control a block resembling a clock. To accurately calculate the time taken by each player to make moves, I store the start time of the game and record the timestamp of every move in the databas ...

Is there an issue with logging in to SQL Server due to state management errors

Something interesting to note - when attempting to execute a service from my local machine, I receive an error message stating Login failed for user ''. The user is not associated with trusted SQL Server connection. However, If the service is e ...

Asynchronous JavaScript combined with a for loop

I'm interested in accomplishing a straightforward task using Nodejs and Async. Let's say I have a total of pages, which is 4 in this example. I am looking to send a request 4 times and then execute a callback once all responses have been receive ...

Trouble with apostrophes rendering in JavaScript on WordPress posts

My current challenge involves adding a post to Wordpress using an external script. This post includes a JavaScript section that contains an iframe for displaying movies. Knowing that Wordpress splits default tags, I have implemented a special plugin to han ...

What is the best way to retrieve JSON data in ReactJS through ExpressJS?

Exploring the realms of reactjs and expressjs, I am seeking guidance on how to extract data from reactjs and store it in a variable. My current achievement includes successfully executing res.send to display the data. app.get('*', (req, res) =& ...

Steps to show submenus upon hovering over the main menu items

I am trying to create a vertical menu with multiple levels using HTML and CSS. Here is the code I have written so far: <ul> <li>Level 1 menu <ul> <li>Level 2 item</li> <li>Level 2 item</li&g ...

What is the best way to implement a Navbar link in React.js?

I am currently working on developing a website using Reactjs. I have successfully created a Navbar with two links - Home and Contact. However, when I click on the Contact link, although the URL changes accordingly, the page itself does not update. I have s ...

What are the best practices for utilizing databases with both Javascript and JSF frameworks?

I am currently following the recommendations provided by @BalusC, with additional guidance available here. (The reason I'm posting this here is because it's not related to my previous question). My goal is to retrieve data from my database and d ...

What is the best way to apply a class to the grandparent div of an element in AngularJS?

Currently, I have a dynamically generated list of tests: <script id="TestsTemplate" type="text/ng-template"> <article class="tests-main"> <section class="tests"> <div class="test" ng-repeat="test in ...

Having difficulty validating the field accurately with Angular.js

In order to validate the input field in accordance with the user's needs using AngularJS, I have shared my code below: <div ng-class="{ 'myError': billdata.longitude.$touched && billdata.longitude.$invalid }"> <input type ...