Cookillian and JavaScript

on June 12, 2012 in Projects with 2 comments by

By default, Cookillian will delete cookies that are set by WordPress (ie., wp-settings-*) and other WordPress plugins. As JavaScript generally lies outside the realm of WordPress, the idea is that certain scripts, such as Google Analytics, are removed from the website and into the Header or Footer fields of Cookillian’s JavaScript section. This prevents the script from loading when the visitor has not (yet) given permission to receive cookies.

This is the preferred method, as it gives greater control over the cookies set by third party scripts. As mentioned, Google Analytics is one such script that should be moved, and is probably easiest to accomplish. But there are some that require a bit more work, like the Twitter Tweet button and Google AdSense, which I will explain next.

I will also provide a sample code that with the help of Cookillian will delete local cookies set by existing JavaScript, to help ease the transition.

Tweet Button

The original code provided by Twitter for the Tweet button is the following:

<a href="https://twitter.com/share" data-lang="en">Tweet</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>

This bit of code is in fact two parts: a regular link with the word “Tweet” to share a URL on Twitter, and a script that replaces this link with a pretty button and a share counter.

Because the JavaScript only needs to be called once for all such links, we can simply remove the <script> portion from the code above, and place it in the Footer field of Cookillian’s JavaScript section. It should not be placed in the Header field though, as it would otherwise be run too soon by the browser.

When cookies are blocked, the script by Twitter is not permitted to run and the regular “Tweet” link will remain as-is. When cookies are permitted, the script is allowed to run, and the simple links are transformed into the more familiar buttons with counters.

This also works for other scripts that replace a simple link with buttons, such as Facebook’s “Like” button. However, some scripts must be run at certain locations. Google AdSense is one such example, and will require a bit more work still.

Google AdSense

The following is a sample of the code provided by Google AdSense. It is to be placed where the advertisement should be displayed:

<script type="text/javascript"><!--
  google_ad_client = "ca-pub-xxxxxxxxxxxxxxxx";
  /* 160x600, created 11/1/08 */
  google_ad_slot = "000000000000";
  google_ad_width = 160;
  google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>

When this code is run by the browser, it will add the advertisement where this code is located. For this reason, it cannot be moved into the Footer or Header fields of Cookillian’s JavaScript section. Instead, one needs to use one of Cookillian’s API methods to accomplish this.

Selective text insertion

One API method available in Cookillian is cookillian.insertString(), and can be used to insert text, including JavaScript, at a specified location. It takes 4 parameters:

  • where – the CSS selector where to insert the string,
  • true_string – The string (text) to use when the 4th parameter (tf_value) is true,
  • false_string – The string to use when the 4th parameter is false,
  • tf_value – An optional boolean value (true or false) or name of a Cookillian variable, used to indicate which string to use. If this is omitted, it will use Cookillian’s blocked_cookies variable by default.

Using it is very simple, and it automatically handles any asynchronous AJAX calls made by Cookillian. Here’s an example:

Cookies are currently <span id="insert_here"></span>.
<script type="text/javascript">cookillian.insertString("#insert_here", "disabled", "enabled", "blocked_cookies");</script>

This will check the cookillian.blocked_cookies variable when it is ready, and add will “disabled” to the text if cookies are blocked (true), or “enabled” if they are not (false). As the text can also include JavaScript, we can use this function to add the Google AdSense code when cookies are permitted.

 

Any text needs to be enclosed in a single or double quote. The JavaScript code may already contain single or double quotes, and therefore need to be “escaped”.  Freeformatter.com provides a quick and easy to use tool to perform the escaping.

The following is what the code will look like for Google AdSense:

<span id="google_ad_1"></span>
<script type="text/javascript">
cookillian.insertString(
"#google_ad_1", // Where
"",
"<script type="text/javascript"><!--
google_ad_client = "ca-pub-xxxxxxxxxxxxxxxx";
/* 160x600, created 11/1/08 */
google_ad_slot = "000000000000";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>"
);

This code will insert nothing if cookies are blocked. You could perhaps use that to display an alternative advertisement. If cookies are not blocked, it will run the provided Google AdSense code as usual. As you may have noticed, I left out the 4th parameter, as this is the cookillian.blocked_cookies variable by default.

Important! It is important to note that according to the Google AdSense program policies, their provided code should not be altered to behave in a different way.
An ID attribute, as seen in the <span> tag, can only be used once on a page. For each ad, you should use a different ID (you could increment the last number, for example).

Periodic Clean-up

The following is an example using the Cookillian API, which periodically checks if new local cookies have been set and delete them (unless they’re required). It will also skip this periodic clean-up if cookies are permitted.

(function($){
    $(document).on('cookillian_ready', function() {
        function cookiesSqueakyClean() {
            // Check if cookies aren't allowed but present
            if (cookillian.blocked_cookies && document.cookie) {
                // If we haven't "seen" these cookies before, try delete them
                if (typeof document.last_seen_cookies === "undefined" ||
                    document.last_seen_cookies !== document.cookie) {
                    cookillian.deleteCookies();
                }

                // Anything left is likely to be "required",
                // and we save these for the next check
                document.last_seen_cookies = document.cookie;
            }
            setTimeout(cookiesSqueakyClean, 1000);
        }
        cookiesSqueakyClean();
    });
}(jQuery));

The periodic clean-up will handle cookies that are “local” only, that is, cookies that belong to the same domain as the visiting website. Cookies for other domains cannot be handled (and is not a limitation, but a security feature implemented by browsers).

Again, the preferred method is to use the selective insertion of Javascript using the API or in the provided fields, as this gives greater control over 3rd party cookies.

 

2 comments

  1. posted on Dec 06, 2012 at 1:15 PM  |  reply

    Ok, got that to work. Anyway a very helpfull plugin. Best H.

  2. posted on Dec 05, 2012 at 8:03 PM  |  reply

    Dear Myatu, I followed your ad sense example to implement piwik and used freeformatter to escape the javascript, but have no luck. Any idea? Best Hartmut

Join the discussion

Your email address will not be published. Required fields are marked *