Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot set cookies in Javascript

I have a very simple line of code that set and read a cookie. I kept getting empty value for my cookie and have no understanding why. I have cookie enabled and know that cookies work on the browser.

<HTML>     <HEAD>         <TITLE>Hello World</TITLE>     </HEAD>     <BODY>         <SCRIPT type="text/javascript">             document.cookie = "ding=dong";         </SCRIPT>         <script type="text/javascript">             alert(document.cookie);         </script>     </BODY> </HTML> 
like image 813
KMC Avatar asked Nov 12 '11 14:11

KMC


People also ask

Can you set a cookie in JavaScript?

Create a Cookie with JavaScriptJavaScript can create, read, and delete cookies with the document. cookie property. With JavaScript, a cookie can be created like this: document.

Why is cookie not being set?

Check out the OPTIONS response header ACCESS-CONTROL-ALLOW-CREDENTIAL whether it is set to true . If the server doesn't allow credentials being sent along, the browser will just not attach cookies and authorization headers. So this could be another reason why the cookies are missing in the POST cross-site request.

How do you set cookies?

Cookies are usually set by a web-server using the response Set-Cookie HTTP-header. Then, the browser automatically adds them to (almost) every request to the same domain using the Cookie HTTP-header.

How do I accept cookies in JavaScript?

At the top right corner, click Settings and more , then choose Settings. Select Cookies and site permissions. Click Manage and delete cookies and site data, then turn ON Allow sites to save and read cookie data (recommended). Select JavaScript under Site permissions, then turn ON Allowed (recommended).


1 Answers

Recently I stumbled upon a similar issue. My script couldn't store a cookie in Chromium, although it worked well on all other major browsers. After some googling it turned out that Chrome ignores cookies from local pages. After I uploaded the page to remote server code magically started to work.

like image 142
Dmitry Vyal Avatar answered Sep 27 '22 00:09

Dmitry Vyal