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 using Google Tag Manager. 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.
- Install Google Tag Manager by putting gtm tracking code into iframe html code
- Identify form id or form class of the form you want to track
- Create Trigger – Form Submission equals :Form id/class
- 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>
- 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>
- Create DataLayerVariable for form – dlv-form
postmessageData.form
- Create Tag GA Event Tag
Category : FormSubmit
Action: dlv-form
Choose Trigger : Custom event – iframeformSubmit
- 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 regarding iframe google tag manager. Also comment if you want me to share any other tutorial in my blog.