track forms through gtm

Track iFrame Forms with Google Tag Manager

How to track iFrame forms with Google Tag Manager.

This is much requested tutorial where I will tell you how to track iframe within our website. Let me tell you first about iframe. iFrame is basically a third party code or website within our website. Before going forward I am sure you have access to that iframe code and you can make changes there.

Basically, We are here using postmessage api of browser which allows us communicate between iframes. Below is step by  step tutorial to track iframe forms using google tag manager.

  1. Install Google Tag Manager by putting gtm tracking code into iframe html code
  2. Identify form id or form class of the form you want to track
  3. Create Trigger – Form Submission equals :Form id/class
  4. Create Tag – Sender Postmessage choose above trigger
<script>
  try {
    var postObject = JSON.stringify({
      event: 'iframeFormSubmit',
      form: 'Contact Us'
    });
    parent.postMessage(postObject, 'https://www.yourmainsite.com');
  } catch(e) {
    window.console && window.console.log(e);
  }
</script>


  1. Create Tag – Listener postmessages
<script type="text/javascript">
  (function(window) {

    addEvent(window, 'message', function(message) {
    try{
     var data = JSON.parse(message.data);
     var dataLayer = window.dataLayer || (window.dataLayer = []);
     if (data.event) {
       dataLayer.push({
         'event': data.event,
         'postMessageData': data
       });
     }
    }catch(e){}
    });
 
    //Cross-Browser event listener
    function addEvent(el, evt, fn){
     if (el.addEventListener) {
       el.addEventListener(evt, fn);
     } else if (el.attachEvent){
       el.attachEvent('on' + evt, function(evt) {
      fn.call(el, evt);
       });
     } else if (typeof el['on' + evt] === 'undefined' || el['on' + evt] === null) {
       el['on' + evt] = function(evt) {
         fn.call(el, evt);
       };
     }
    }
  })(window);
</script>


  1. Create DataLayerVariable for form – dlv-form

postmessageData.form

 

  1. Create Tag GA Event Tag

Category : FormSubmit

Action: dlv-form

Choose Trigger : Custom event – iframeformSubmit

 

  1. You are done. You can see the event appears in the Google analytics real time events sections. You can further use those event fields to create goal.

 

Reach out to me in case of any query or concerns. Also comment if you want me to share any other tutorial in my blog.

Leave a Reply

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