Use the dataLayer
When your website uses Google Tag Manager, the script also sends the events of the dataLayer. You do not need more code.
What the script does
- The script reads each push to
window.dataLayer, also the pushes before the script loads. - A push with an
eventkey becomes an event with the same name, in lowercase. For example,generate_leadbecomesgenerate_lead. - A push in the
gtagarray form, for example['event', 'purchase', { value: 10 }], becomes the eventpurchasewith the propertyvalue. - The other keys of the push become properties.
- The script ignores the events and the keys that start with
gtm., for examplegtm.jsandgtm.dom. - Two script tags on one page do not send one event two times. The first client reads the
dataLayer, and the second client writes a warning in the console.
Example
This push:
dataLayer.push({ event: 'generate_lead', form: 'demo', value: 100 });sends the event generate_lead with the properties form and value.
Procedure: select the dataLayer events
- Set
data-datalayer-includeto the event names to send, with a comma between each name. A*matches each character at its position. - Set
data-datalayer-excludeto the event names to stop. The exclude list wins over the include list.
An empty include list sends each name that the exclude list does not stop. The client always stops the names that start with gtm..
Procedure: identify a known visitor
- Keep the default keys, or set
data-datalayer-email-keyanddata-datalayer-user-id-keyto the keys that your site pushes. - Push the value in a
dataLayerentry, for exampledataLayer.push({ event: 'login', user_id: 'u-17' }).
The default keys are user_data.email for the email and user_id for the product user ID. A key can be a nested key, with a dot between the parts. An entry can have both keys, and the client then sends one identify with both values. The client sends each change of a value one time. Set a key to an empty value to stop the identify from that key.
The identify from the dataLayer goes only when the site grants analytics. Before the grant, the client keeps only the last value of each key in memory. It sends that value when the site grants analytics, and it drops the value when the site denies analytics.
Procedure: stop the dataLayer events
- Set
data-datalayer="off"on the script tag, or set the field dataLayer to off in the GTM template.
Result
The script stops the events of the dataLayer. Consent from the dataLayer still operates. Refer to Set consent.