How to use JavaScript to set cookies for a specific page only?

JavascriptWeb DevelopmentFront End Technology

To set cookies for a specific page, you need to use the “window.location.pathname” property. The property returns the path and filename of the current page.


You can try to run the following code to implement cookies for a specific page −

Live Demo

            function WriteCookie() {
               if( document.myform.customer.value == "" ) {
                  alert("Enter some value!");
               cookievalue= escape(document.myform.customer.value) + ";";
               var myPath = window.location.pathname;

               document.cookie="name=" + cookievalue + ";path=myPath";
               document.write ("Setting Cookies : " + "name=" + cookievalue );
      <form name = "myform" action = "">
         Enter name: <input type="text" name="customer"/>
         <input type = "button"  value = "Set Cookie"  onclick = "WriteCookie();"/>
Published on 31-Jan-2018 11:04:42