mdn / content

The content behind MDN Web Docs
https://developer.mozilla.org
Other
9.21k stars 22.49k forks source link

Issue with "Document.cookie": (short summary here please) #2223

Closed spanezz closed 3 years ago

spanezz commented 3 years ago

MDN URL: https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie

What information was incorrect, unhelpful, or incomplete?

The code sample to extract a cookie matches on cookie name prefixes, not on full cookie names

This is the current sample:

const cookieValue = document.cookie
  .split('; ')
  .find(row => row.startsWith('test2'))
  .split('=')[1];

As it is, it would happily match a cookie named test20. Using .find(row => row.startsWith('test2=')) would match the exact cookie name.

The code gives the expected result in the specific context of that example, but if people copypaste it as a simple way to read cookies in JavaScript, they might be getting surprising results.

Specific section or headline?

"Example #2: Get a sample cookie named test2"

What did you expect to see?

Something like this:

const cookieValue = document.cookie
  .split('; ')
  .find(row => row.startsWith('test2='))
  .split('=')[1];

Did you test this? If so, how?

I tested my proposed version in the program I'm writing

MDN Content page report details * Folder: `en-us/web/api/document/cookie` * MDN URL: https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie * GitHub URL: https://github.com/mdn/content/blob/master/files/en-us/web/api/document/cookie/index.html * Last commit: https://github.com/mdn/content/commit/3c8dd140b3925bf8f7b00d0972f27c5760f5c6a3 * Document last modified: 2021-01-15T13:22:56.000Z
mohitdmak commented 3 years ago

I have added a commit to a previously opened PR.

wbamberg commented 3 years ago

Fixed by https://github.com/mdn/content/pull/2209. Thanks, @mohitdmak !