How to create domain-based cookies using JavaScript?


To create a domain-based cookie, set the domain and path attribute on your cookie, like −

domain=.example.com

Example

You can try to run the following code to learn how to create domain-based cookies −

Live Demo

<html>
   <head>
      <script>
         <!--
            function WriteCookie() {
               if( document.myform.customer.value == "" ){
                  alert("Enter some value!");
                  return;
               }
               cookievalue= escape(document.myform.customer.value) + ";";
               document.cookie = "name=" + cookievalue + ";
               domain=.example.com;path=/";
               document.write ("Setting Cookies : " + "name=" + cookievalue );
            }
         //-->
      </script>
   </head>
   <body>
      <form name = "myform" action = "">
         Enter name: <input type="text" name="customer"/>
         <input type="button" value="Set Cookie" onclick="WriteCookie();"/>
      </form>
   </body>
</html>

Updated on: 16-Jun-2020

189 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements