Updated: January 12, 2025
This time I will share how to use GTM to track user copying behavior.
The principle is to inject javascript through custom HTML to monitor whether the user has copying behavior. If so, send data through dataLayer.push, and the copied text and text length are passed through data layer variables and sent to GA4.
Step 1 : Custom HTML to inject javascript
In GTM , click「Tags」——「New」——「Choose a tags type to begin setup…」——「Custom HTML」,Name it “HTML-Copy”, and make the following settings:
Source Code:
<span style="font-size: 12pt;"><script> // Declare function to get selected text from document function getSelectionText() { var text = ""; if (window.getSelection) { text = window.getSelection().toString(); } else if (document.selection && document.selection.type != "Control") { text = document.selection.createRange().text; } return text; } // Declare function on copy event document.addEventListener("copy", function(e){ dataLayer.push({ "event": "textCopied", "clipboardText": getSelectionText(), "clipboardLength": getSelectionText().length }); }); </script> </span>
If you want to track only copied emails or phone numbers, you can make some restrictions and add a judgment to send an event only when the copied text is equal to a specific value.
Step 2 : Set Up the Trigger
In GTM , click「Triggers」——「New」——「Choose a trigger type to begin setup…」——「Custom Event」,Name it “textCopied”, and make the following settings:
Step 3 : Set Up the DataLayer Variables
In GTM , click「Variables」——「New」——「Choose a variables type to begin setup…」——「Data Layer Variable」,Name it “DL – Clipboard Text”, and make the following settings:
Similarly, set DL – Clipboard Length:
Step 4 : Set Up the Tags
In GTM , click「Tags」——「New」——「Choose a tags type to begin setup…」——「Google Analytics: GA4 Event」,Name it “GA4-Event-TextCopy”, and make the following settings:
The event name is TextCopy
Two event parameters TextCopy_text and TextCopy_length are defined to pass the copied content and content length.
Step 5 : Preview and Publish
Next is preview debugging.
You can see that Tags is triggered. Next, check whether the values of the event parameters are correct:
The values of the event parameters are correct and can be published.
Step 6 : Custom Definitions
We have set the event parameters TextCopy_text and TextCopy_length. Next, we need to register the event parameters in GA4
- TextCopy_text is event scope custom dimensions
- TextCopy_length is event scope custom metrics
In GA4,click「Admin」——「Custom definitions」——「Create custom dimension」, then do the following configuration:
In GA4,click「Admin」——「Custom definitions」——「Custom metrics」——「Create custom metrics」, then do the following configuration:
Read More: GA4 Event Tracking Series ⓪ — Rules and Limits for GA4 Events
Step 7 : Verify Data in Explore
Generally, after 24 hours, you can see the data in GA4, such as: