Modifying web analytics through Liferay Control Panel


Recently we needed to integrate additional web analytics tool on the Liferay site.  The standard way of modifying velocity templates in the theme and their redeployment does not allow quick testing turnaround and cannot be done using the browser only.

“Standard” Google Analytics integration is quite simple since it is supported as out-of-the-box functionallity – portal administrator just needs to navigate to Control Panel->Portal->Sites->Site Settings->Analytics and enter tracking code. When needing a more advanced tracking using custom variables, or a different web analytics tool, it is necessary to add a custom Javascript code to site pages. This can be achieved by using Control Panel->Site Pages->JavaScript, where we can paste custom made code that will be enclosed in the script HTML element at the bottom of the page. There are two drawbacks with such a technique. The first is that javascript will be executed only if page is completely loaded (it refers to the original HTML content, not all referenced resources). The second is that it is not possible to mix HTML and Javascript. For example, clicky provides the following integration snippet:

<script src="//" type="text/javascript"></script>
<script type="text/javascript">try{ clicky.init(12345678); }catch(e){}</script>
<noscript><p><img alt="Clicky" width="1" height="1" src="//" /></p></noscript>

The integration HTML includes loading of javascript resource and static URL that is loaded from the web analytics server. This HTML code can be dynamically generated from Javascript using HTML DOM:

var footer= document.getElementsByTagName('footer')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= '//';

var img= document.createElement('img');
img.src= '//';

This technique, when combined with possibility to override CSS defined by the theme for the site pages, enables a site administrator much more than just adding new analytics code. It enables quick runtime changes of the page layout, header and the footer elements without assistance of the developer to rebuild and redeploy the theme.