An iframe form is a web form embedded within a webpage using an HTML iframe element. It allows external forms to be seamlessly displayed and interacted with on a site. However, collecting data from these forms can be tricky because the tracker doesn’t have direct access to the elements inside the iframe. Fortunately, there is a clever solution for this. The iframe element can send messages (window.postMessage()) to your site. For example, when a visitor submits a form in the iframe, it can send a message that includes one of Piwik PRO’s JavaScript API methods. Piwik PRO’s tracker can then receive this message and interpret it as, for example, a custom event.
In this article, we’ll explain how you can collect data from iframe forms.
Before you start
Here are a few things to know before you start:
- You need to have access to your iframe. The iframe can’t be a third-party element.
- When sending a message from your iframe, you can use any JavaScript API method from Piwik PRO. However, the most commonly used method is trackEvent(), which is used to track custom events.
Collect data from iframe forms
To collect data from iframe forms, follow these steps:
- Log in to Piwik PRO.
- Go to Menu > Tag Manager.
- Navigate to Tags.
- Select the following tag: Custom code (async).
- In Tag code, paste our custom code with the iframe handler that will read messages from iframes:
<script> (function () { var pushToAnalytics;pushToAnalytics=function(){"use strict";var t={117:function(t,n){n.default=function(t){window._paq=window._paq||[],window._paq.push(t)}}},n={};return function r(o){if(n[o])return n[o].exports;var u=n[o]={exports:{}};return t[o](u,u.exports,r),u.exports}(117)}().default; window.addEventListener('message', function(event){ if(event.data.type === "PiwikPRO"){ pushToAnalytics(event.data.payload); } }, false); })(); </script>
- Add the following trigger: Page view. And then set it up to fire on all pages with iframe forms.
- Click Save.
- Test your tag in debug mode.
- When you’re happy with how the tag works, click Publish.
- After setting up the iframe handler, you should include a message in the iframe script to collect data from it. Add the following line to your iframe script at the desired location:
window.parent.postMessage({ type: "PiwikPRO", payload: [command] }, "*")
Parameters
command (string, required)
An array containing our JavaScript methods.Example:
window.parent.postMessage({ type: 'PiwikPRO', payload: ["trackEvent", "assignment", "submitted", "math 4", 10] }, '*');
This example shows the use of a trackEvent() method that tracks custom events. We recommend using it to collect data from iframe forms.
- You’re all set! Your iframe forms are now being tracked. If you used the trackEvent() method, you can easily find your data in Analytics > Reports > Custom reports.