Software, your way.
How To Get Good Custom Software
(Download)
(PDF)
burger menu icon
WillMaster

WillMaster > LibraryWebsite Development and Maintenance

FREE! Coding tips, tricks, and treasures.

Possibilities weekly ezine

Get the weekly email website developers read:

 

Your email address

name@example.com
YES! Send Possibilities every week!

Cookie Control With JavaScript for Developers

One of the things about browsers is it's generally impossible to independently set a cookie.

Web pages set the cookie or cookies they are programmed to set. You have no control.

The JavaScript software with this article, JS Cookie Control, gives you control. This software has been distilled from a long history of evolvement into something ridiculously easy to use. It even works on WordPress posts and pages.

The evolvement began way back (1998) when I was learning about cookies and how they work.

At first, I studied the specifications. Then, I learned how to read and set cookies with Perl CGI. After that, with JavaScript.

More and more, I developed software with cookies as an essential aspect of functionality. Occasionally I needed to manipulate cookies independent of software being tested. As an example, I sometimes needed to see how the software would behave if the cookie it was using suddenly disappeared.

Thus, stand-alone software able to set, list and delete cookies came into being.

The version immediately before today's JavaScript version is still available. It's PHP software to provide cookie control for site developers.

Today's version is JavaScript and the easiest to use of all previous versions.

As a developer, you've no doubt been in situations where you needed to test certain web pages or software that required a cookie to have been set and available in the browser.

JS Cookie Control comes to the rescue.

With JS Cookie Control, you specify the cookie name, the value, and optionally specify the path and/or the expiration period. Click the button and your browser has the cookie.

The cookie-control JavaScript file can be on any server — even your own. However, the one line of JavaScript required to use JS Cookie Control needs to be in a web page of the domain being inspected. To create or update a page with the line of JavaScript, FTP or other authorized server access is necessary.

When the page with the line of JavaScript is loaded in your browser, you can set, list, and delete cookies.

Here's a screenshot of the in-page control panel containing example cookies and values.

screenshot of JS Cookie Control in-page control panel

To delete a cookie, click or tap its "Delete" button.

To add a cookie, fill in the Add a Cookie form:

  1. A cookie name begins with a letter and is composed of letters, numbers, and/or underscore characters.

  2. The cookie value can be any text content up to 4k.

  3. The cookie path is either Sitewide, which is the document root directory, or Here, which is the directory where the web page with JS Cookie Control is at. Cookies are available to browsers at the directory the cookie is set for and any of its subdirectories.

  4. The cookie duration is the number of days or fraction of days the cookie shall last. The number may be a decimal number. Specify 1.5 for 1½ days duration, as an example, and 0.0417 for approximately 1 hour duration, as another example. With 0 (zero) specified, the cookie will be discarded when the browser is exited.

Click or tap the Add Cookie button to finalize adding the cookie.

To enable JS Cookie Control, two things are required:

  1. Save a JavaScript file (see below) to your server or your client's server. Make a note of its URL.

    This is done once.

  2. Put a line of JavaScript (see further below) into a web page to use the interface. It pulls in the JavaScript of step 1. The line can be in an independent page or temporarily in the page being tested.

    This is done for every location where you will be using JS Cookie Control.

Enablement Step 1:

Here is the JavaScript to save on your server or your client's server.

/*
   JS Cookie Control
   Version 1.0
   February 10, 2017

   Will Bontrager Software LLC
   https://www.willmaster.com/
   Copyright 2017 Will Bontrager Software LLC

   This software is provided "AS IS," without 
   any warranty of any kind, without even any 
   implied warranty such as merchantability 
   or fitness for a particular purpose.
   Will Bontrager Software LLC grants 
   you a royalty free license to use or 
   modify this software provided this 
   notice appears on all copies. 
*/

var JSCC_Cookies = new Object();
var JSCC_CurrentPath = document.URL.replace(/^https?\:\/\/[^\/]*/i,"");
function JSCC_GetCookies()
{
   JSCC_Cookies = Object();
   if(document.cookie.length < 1) { return; }
   var chunks = document.cookie.split(/;/);
   var count = chunks.length;
   for( var i=0; i<count; i++ )
   {
      var s = chunks[i].replace(/^\s*/,"");
      var s = s.replace(/\s*$/,"");
      var ck = s.split('=',2);
      JSCC_Cookies[ck[0]] = decodeURI(ck[1]);
   }
}

function JSCC_DeleteCookie(name)
{
   var now = new Date();
   now.setTime(now.getTime()-(24*60*60*1000));
   var exp = now.toGMTString();
   document.cookie = name + '=0' + '; path='+JSCC_CurrentPath + '; expires=' + exp;
   document.cookie = name + '=0' + '; path=/; expires=' + exp;
   location.href = document.URL;
}

function JSCC_AddCookie()
{
   var name = document.getElementById("JSCC_cookie-name").innerHTML.replace(/<[^>]*>/g,"");
   name = name.replace(/(\&nbsp\;)+/g,"");
   name = name.replace(/^[^a-zA-Z\_]+/,"");
   name = name.replace(/[^a-zA-Z0-9\_]+/g,"");
   var value = document.getElementById("JSCC_cookie-value").innerHTML.replace(/<[^>]*>/g,"");
   value = value.replace(/(\&nbsp\;)+/g," ");
   if( name.length<1 || value.length<1 )
   {
      alert("Both cookie name and cookie value need to be provided.");
      return;
   }
   value = encodeURI(value);
   var path = "/";
   if( document.getElementById("JSCC_cookie-here").checked ) { path = JSCC_CurrentPath; }
   var days = document.getElementById("JSCC_cookie-duration").innerHTML.replace(/[^\d\.]+/g,"");
   var exp = "";
   if( days > 0 )
   {
      var now = new Date();
      now.setTime( now.getTime() + parseInt(days * 24 * 60 * 60 * 1000) );
      exp = '; expires=' + now.toGMTString();
   }
   document.cookie = name + "=" + value + '; path=' + path + exp;
   location.href = document.URL;
}

function JSCC_PresentCurrentCookies()
{
   JSCC_GetCookies();
   document.write('<table border="1" cellpadding="6" cellspacing="0" style="border-collapse:collapse;">');
   document.write('<tr><th colspan="3">Current Cookies</th></tr><tr><th>Name</th><th>Value</th><th>Delete</th></tr>');
   for( var key in JSCC_Cookies )
   {
      if( JSCC_Cookies.hasOwnProperty(key) )
      {
         document.write('<tr><td>' + key + '</td><td>' + JSCC_Cookies[key] + '</td><td><input type="button" value="Delete" onclick="JSCC_DeleteCookie(\'' + key + '\')"></td></tr>');
      }
   }
   document.write('</table>');
   document.write('<div style="margin-top:.3in; border:1px solid black; padding:.5em;"><div style="font-weight:bold;">Add a Cookie</div>');
   document.write('<div style="margin-top:.75em;">Cookie Name:</div>');
   document.write('<div id="JSCC_cookie-name" style="margin-top:.125em; border:1px solid #ccc; border-radius:.25em; padding:.25em;" contenteditable="true" spellcheck="true"></div>');
   document.write('<div style="margin-top:.75em;">Cookie Value:</div>');
   document.write('<div id="JSCC_cookie-value" style="margin-top:.125em; border:1px solid #ccc; border-radius:.25em; padding:.25em; min-height:.3in;" contenteditable="true" spellcheck="true"></div>');
   document.write('<div style="margin-top:.75em;">Cookie path:&thinsp; <input id="JSCC_cookie-sitewide" type="radio" name="aaa" value="sitewide" checked="checked">&thinsp;Sitewide <input id="JSCC_cookie-here" type="radio" name="aaa" value="here">&thinsp;Here</div>');
   document.write('<div style="margin-top:.25em;">Cookie duration: <div id="JSCC_cookie-duration" style="display:inline; border:1px solid #ccc; border-radius:.125em; padding:.125em .5em .125em .5em;" contenteditable="true">&nbsp;0&nbsp;</div>&nbsp;days</div>');
   document.write('<div style="margin-top:.75em;"><input type="button" value="Add Cookie" style="width:100%; box-sizing:border-box;" onclick="JSCC_AddCookie()"></div>');
   document.write('</div>');
}

JSCC_PresentCurrentCookies();

No customization is required.

Name the file JScookieControl.js or other preferred name. Upload it and make a note of its URL.

Enablement Step 2:

To obtain the in-page control panel, put the below line of JavaScript into a web page located in the relevant directory. (Some cookies are accessible only when the web page is in a certain directory.)

There is one customization. See the note that follows.

<script src="http://example.com/JScookieControl.js"></script>

Customize by updating the URL in the JavaScript (colored blue) with the URL of the JScookieControl.js file uploaded in Enablement Step 1.

Load the web page and the in-page control panel is available.

When you need to set a cookie, JS Cookie Control can be used. When you need to figure out what's going on with cookies at a website and using the browser's menu sequence is impractical or feels onerous, there's JS Cookie Control.

Once the JScookieControl.js file is uploaded and its URL noted, a single line of JavaScript will provide the in-page control panel for that page. And it can be used with WordPress.

(This article first appeared in Possibilities ezine.)

Will Bontrager

Was this article helpful to you?
(anonymous form)

Support This Website

Some of our support is from people like you who see the value of all that's offered for FREE at this website.

"Yes, let me contribute."

Amount (USD):

Tap to Choose
Contribution
Method

All information in WillMaster Library articles is presented AS-IS.

We only suggest and recommend what we believe is of value. As remuneration for the time and research involved to provide quality links, we generally use affiliate links when we can. Whenever we link to something not our own, you should assume they are affiliate links or that we benefit in some way.

How Can We Help You? balloons
How Can We Help You?
bullet Custom Programming
bullet Ready-Made Software
bullet Technical Support
bullet Possibilities Newsletter
bullet Website "How-To" Info
bullet Useful Information List

© 1998-2001 William and Mari Bontrager
© 2001-2011 Bontrager Connection, LLC
© 2011-2024 Will Bontrager Software LLC