The Marketing Technologist.

We talk about analytics, code, data science and everything related to marketing technology. Backed by the tech geeks of Greenhouse.

Simplify iFrame tracking for Universal Analytics

Migrating Google Analytics to Universal Analytics is a fairly straight forward process. Especially when you have a tagmanager in place. The only challange is iFrames.

In the default documentation for iFrame tracking Google advices you to use a div-element:

<div id="myiFrame"></div>

<script>
var linker;

function addiFrame(divId, url, opt_hash) {
  return function(tracker) {
    window.linker = window.linker || new window.gaplugins.Linker(tracker);
    var iFrame = document.createElement('iFrame');
    iFrame.src = window.linker.decorate(url, opt_hash);
    document.getElementById(divId).appendChild(iFrame);
  };
}

// Dynamically add the iFrame to the page with proper linker parameters.
ga(addiFrame('myiFrame', 'destination.html'));

</script>

If your website has several iframes, this will require updating all the onsite iframes to div's. With a tagmanager in place, you want to minimize changes that require the website's development team. Luckily, the code mentioned above can be modified to work as the standard Google Analytics iFrame tracking, removing the need for div's:

<iframe id="myiFrame"></iframe>

<script>
var linker;

function addiFrame(iframeId, iframeUrl) {
  return function(tracker) {
    window.linker = window.linker || new window.gaplugins.Linker(tracker);
    var iFrame = document.getElementById(iframeId);
    iFrame.src = window.linker.decorate(iframeUrl);
  };
}

// Dynamically add the iFrame to the page with proper linker parameters.
ga(addiFrame('myiFrame', 'destination.html'));

</script>

Please note that the iFrame src attribute must be empty by default. If it is not empty when loading the code, Universal Analytics won't be able to pass the information correctly. You'll also need to add the referring domain (the page on which your iframe will be loaded) to the referral exclusion list.

With this small change to the Universal Analytics iFrame tracking function, you are ready to migrate without any onsite changes.