0

'document.cookie' in JavaScript does not work without a web server. Using the protocol for local file-access 'document.cookie' will always contain an empty string.

Please see the accepted answer in this StackOverflow Question!

As far as I know are cookies text-files stored in some sub-directory of the particular used browser. Containing key-value pairs.

So, after setting a cookie it should be there on the client-side.

Why has a web server to be involved?

I have made myself this demo:

writeMessage(); // Call the function when page is loaded. => No cookie there.

function writeMessage() {
  var message;

  document.cookie.indexOf('foo') === -1 ?
    message = 'Cookie does not exist.' :
    message = 'Cookie is there!';

  document.querySelector('div').innerHTML = message
}

document.querySelector('button').addEventListener('click', () => {
  document.cookie = "foo=bar";
  writeMessage(); // Call the function again when the cookie has been set.
});
<div class="message"></div>
<button>Set Cookie</button>

When the button is clicked then the cookie is set.

Then the function checks if a cookie exists. It finds that this is true and shows the according message.

!! There haven't been a second request to the web server !!

So why doesn't work cookies when using file URI scheme for accessing the page?

cluster1
  • 4,968
  • 6
  • 32
  • 49
  • There's no spec that defines this behavior. It's a feature (presumably a security feature) in Chrome. You can enable local cookies when you run Chrome with a flag. – Madara's Ghost Jun 25 '17 at 07:15
  • Okay. It is caused by the browser vendors and has nothing to do with the HTTP-protocol itself. Thanks. That explains it. :) – cluster1 Jun 25 '17 at 07:54

0 Answers0