I am creating a GA4 custom event tag and the code below works when someone copies any text on the page. However, I only want to track when someone copies the full URL of the current page in the browser. Any ideas on how to modify the script?
Thank you!
<script>
document.addEventListener('copy', function(){
var selection = window.getSelection().toString();
window.dataLayer.push({
'event': "copyText",
'copiedText': selection
});
});
</script>
2
Answers
When someone copies the URL in their browser that is a system level event that’s not possible to track with client side JavaScript.
So the answer: this is not possible. You would need to make a custom browser to be able to track what users do with the browser outside of a webpage.
However, as a workaround you could track (based on user actions only like on click onscroll etc.) What their current clipboard data contains, as plain text.
The first time you call this, the browser will prompt the user if they want to share their clipboard data.
You can check if the data is equal to the URL of the website.
If it’s not, in general, then you know they haven’t copied the URL.
Then sometimes if, when you check, you see that the clipboard data is equal to the URL, then you know they have copied it some time between when you checked last and the present moment.
Keep track of different timestamps of when they have or have not copied it in some kind of array, or simply pass that timestamp, when you checked it and it matches the URL, as a new tracking event, then make sure to only make another event if you discover that they have some other content pasted in their chipboard at some point.
So to simplify, first they have not copied it. Then through different checks in user events you find they have copied it — keep track of that timestamp, maybe set a Boolean variable
copiedIt
to true, but only if it was false before, and at that time, add the new event.Then if you find they have something else copied, set the
copiedIt
Boolean to false. Then the process should repeat.More details out reading clipboard data
As I said in my comment, you can try to compare the copied text to the current page’s URL.
Also users might unintentionally copy the URL with leading or trailing white space. so use the trim()
and to test, you can add a try catch: