When trying to access the page via file://, the cookies are not functioning properly

My HTML code is functioning properly in Firefox and even on the W3Schools website when tested using their editor in Chrome. However, when I run my code in Chrome from Notepad++, it doesn't seem to work. It appears that the body onload event is not triggering because I am not receiving the alert message. My Chrome browser is updated to the latest version. Any assistance in resolving this issue would be greatly appreciated.

<!DOCTYPE html>
<html>
<head>
<script>
function setCookie(cname, cvalue, exdays){
  var d = new Date();
  d.setTime(d.getTime() + (exdays * 24 *60 * 60 * 1000));
  var expires = "expires=" + d.toUTCString();
  document.cookie = cname + "=" + cvalue + "; " + expires;
}
function f(){
  var user = prompt("What is your name?", "");
  if(user != "" && user!=null){
    setCookie("username", user, 30);
  }
}
function getC(cname){
  var name = cname + "=";
  var ca = document.cookie.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 "";
}
function checkcookie(){
  var user = getC("username");
  if (user != ""){
    alert("Welcome back " + user);
  }
}
</script>
</head>
<body onLoad="checkcookie()">

<input type="button" onclick="f()" value="Click">
</body>
</html>

Answer №1

It is a well-known fact that using the file:// protocol does not guarantee proper functioning with cookies. This is because cookies require three essential elements:

  • A name-value pair containing the actual data
  • An expiry date after which it is no longer valid
  • The domain and path of the server it should be sent to

The domain specifies to the browser which domain the cookie should be sent to. Without specifying it, the domain defaults to the page that sets the cookie.

When using the file:// protocol, there is no specified domain.

Although some browsers like FireFox and IE may have workarounds for this issue, testing your code on these browsers will show that they do not handle cookies in the same manner as when hosted on a webserver.

To ensure proper cross-browser compatibility testing, it is recommended to use the http:// protocol. You can start by setting up a jsfiddle or hosting your code on a web server (such as IIS or Apache).

For more information on working with cookies, refer to: quircksmode

If you are determined to make it work on Chrome using the file:// protocol, there may be a slim chance if you correctly define the path.

  • Path: Ensure proper escaping of the path =>
    encodeURIComponent(document.domain)
    or "c:/my%20folder/index.html" (something along these lines, although the reliability of this information is questionable)
  • Domain: "/" (not much else you can try here)

Answer №2

Make sure your user variable is an empty string.

Include an alert at the beginning of your validateCookies() function to confirm that body onload is functioning.

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

Trouble with CSS and JS tabs not activating when clicked?

I am experiencing issues with a navigation (organized in tabs) that is not functioning on this page, but it works correctly on this page using the same method for inclusion. When clicking "Norway" on the top left, the navigation opens but switching to the ...

Evolving the appearance of every vacant element

Currently, I am working on a project that allows users to add items. To facilitate this process, I have included an "add another" button which enables them to include additional items all at once. In order to validate the form and save values to the datab ...

"Encountering issues with react-swipable-views when attempting to use it

I'm currently working on implementing react-swipable-views into my React application, but I encountered a specific error message: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite component ...

PHP code to export data to a CSV file containing Chinese characters

I attempted the following: $name = iconv("utf-8", "GB18030", $value["name"]); Opening in a text editor and changing the encoding Importing into Excel while adjusting the encoding This process involves PHP and JavaScript: Here is my PHP code: echo & ...

The functionality for tabbed content seems to be malfunctioning on Chrome and Firefox, however it works perfectly

In my index.js file, I have various functions set up like so: // a and b is placed at index.jsp $("#a").click(function (){ //this works on index.jsp and display.jsp(where the servlets forwards it). $("#b").load('servletA.html?action=dis ...

Update various components within a container

I have incorporated a function that automatically loads and refreshes content within a div every 10 seconds. Here is the script: $(function () { var timer, updateContent; function resetTimer() { if (timer) { window.clearTimeout(timer); ...

Receiving an error when attempting to import a function and access props using the "this" keyword: "TypeError: Unable to retrieve property 'renderElapsedString' as it is undefined"

Just started using React and working on a time tracking app based on the teachings of FullStackReact. Instead of Create Class, I opted for the ES6 'extends' module. However, I've encountered an error that has got me stumped. Error: Unable ...

Can you provide guidance on implementing StyledComponents within the app folder of Next.js version 13?

Quoting information from the Next.js documentation: Attention: CSS-in-JS libraries that rely on runtime JavaScript are currently not compatible with Server Components. The following libraries are supported in Client Components within the app directory: s ...

Identifying duplicate values in an array of objects using JavaScript

I am facing an issue with my array that collects data from a spreadsheet into studentCCAList. Sometimes, a student may have multiple subjects. For example, Name: Joseph Subject: English Name: Peter Math Name: Joseph Subject: Science My concern i ...

Stacking sheets of hole-punched paper on top of one another, create a visually captivating

I am in search of a way to create those distinctive black dots with papers displayed here: body { background: linear-gradient(#ccc, #fff); font: 14px sans-serif; padding: 20px; } .letter { background: #fff; box-shadow: 0 0 10px rgba ...

comparative analysis: nextjs getServerSideProps vs direct API calls

Trying to grasp the fundamental distinction between getServerSideProps and utilizing useSWR directly within the page component. If I implement the following code snippet in getServerSideProps: export const getServerSideProps = async () => { try { ...

Changing the information of objects stored in arrays using React Three Fiber

My challenge is with an array of roundedBox geometry shapes called myShape. I am trying to figure out if it's possible to change the position of one of the shapes within the array without creating a new shape altogether. Ideally, I would like to updat ...

Transform a string into an object

How can I convert a string into an object with error details? const er= {'username': [ErrorDetail(string='A user with that username already exists.', code='unique')], 'email': [ErrorDetail(string='user with thi ...

javascript update HTML content

Hello, I am trying to call a function called changeDivHTML which passes an image. <a href="javascript:void(0)" onclick="changeDivHTML(<img src='.DIR_WS_IMAGES .$addimages_images[$item]['popimage'].'>)"> This function ad ...

What is the best method for concealing a specific element on the screen using ReactJS?

I'm looking for a way to have text displayed on the screen that is only hidden when a button is pressed, but I'm struggling to figure it out. I had the idea of using useState in this way: const [textVisibility, setTextVisibility] = useState(true) ...

Fill in datatable with information from a JSON array if there are missing values in certain columns

My goal is to populate a datatable in JavaScript. Currently, I am able to do so, but some of the last rows have blank columns which are populated first. I attempted to fill those blank columns, and then the data populates in order. Here is an example of my ...

Is there a way to remove CSS based on the generated HTML code?

Currently tackling a project in Next.js involving custom SCSS, Bootstrap SCSS, and React-Bootstrap. Struggling with the bloated size of our main.scss file due to unused CSS. After observing that 95% of the CSS is not utilized, I aim to eliminate all unnec ...

Retrieve the Data from Input Fields with Matching Classes and Transmit to a Script Using AJAX Request

I am working on a form that includes multiple input fields: <input type="text" class="date" name="date[]" onkeyup="showHint()" /> <input type="text" class="date" name="date[]" onkeyup="showHint()" /> <input type="text" class="date" name="da ...

Confirming user banking information is necessary solely for account activation through Stripe

I've been working with NodeJS and ExpressJS Is there a way to set up account verification with Stripe? I want to confirm that users have bank accounts without charging them. What kind of information can I access through this verification process? My ...

Route.get() is looking for a callback function, but instead received an [object Promise]

Currently, I am in the process of developing a REST API using express and following the architecture outlined in this particular article. Essentially, the setup involves a router that calls a controller. Let me provide you with an example of how a call is ...