Sub topic 9
Tagging AI visits with a custom event
The custom channel group from the earlier chapter labels sessions that arrive with a recognisable source. A custom event records a separate fact: this page view came from an AI assistant, and here is which one. The event does not replace the channel group. It adds a signal that you control, and you can use it in explorations, audiences, and key events.
This chapter assumes you have these prerequisites:
- You can read
document.referrerin browser JavaScript. - You know what a UTM parameter is.
- You have a GA4 web data stream and either Google Tag Manager (GTM) access or the ability to edit your site's
gtag.jssnippet. - You have Editor access to the GA4 property. Registering a custom dimension needs Editor.
Why add an event when you have a channel group
A channel group is computed from the session's source and medium. An event is sent from the browser and carries whatever parameters you choose. This gives you three things the channel group does not.
- An explicit assistant name. Your event parameter can say
ChatGPTorPerplexityinstead of leaving you to read raw source strings. - A signal that works on the landing page itself. Event-scoped data attaches to the exact page view where the referrer was present.
- A basis for audiences and key events. You can build an audience of users who ever triggered
ai_assistant_visit, or mark the event as a key event.
The event has the same blind spot as the channel group. If the browser sends no referrer and the link has no UTM parameter, your code has nothing to detect. Tagging cannot recover information that never reached the page.
What the browser tells your code
When a visitor clicks a link in an assistant, two signals can reach your page.
document.referrer. This is the URL of the page that linked to you. Under the default referrer policy (strict-origin-when-cross-origin) a cross-origin referrer is trimmed to the origin, for examplehttps://chatgpt.com/. The hostname is still usable, which is all you need.- Query parameters on the landing URL. Some assistants append a tag such as
utm_source=chatgpt.comto outbound links. This survives even when the referrer is stripped, for example by anoreferrerlink attribute or a privacy setting.
Your code should check both, with the query parameter as a fallback.
Option 1: a gtag snippet
The snippet below assumes the standard Google tag is already on the page, so gtag is defined. Place it after the Google tag snippet, and make sure it runs on every page, not only the homepage.
const AI_HOSTS = {
'chatgpt.com': 'ChatGPT',
'chat.openai.com': 'ChatGPT',
'gemini.google.com': 'Gemini',
'perplexity.ai': 'Perplexity',
'www.perplexity.ai': 'Perplexity',
'copilot.microsoft.com': 'Copilot',
'claude.ai': 'Claude'
};
function hostFromUrl(value) {
try {
return new URL(value).hostname;
} catch (e) {
return '';
}
}
function detectAssistant() {
// 1. Referrer host
const fromReferrer = AI_HOSTS[hostFromUrl(document.referrer)];
if (fromReferrer) {
return { name: fromReferrer, via: 'referrer' };
}
// 2. utm_source fallback, for example utm_source=chatgpt.com
const utmSource = new URLSearchParams(window.location.search).get('utm_source');
if (utmSource) {
const fromUtm = AI_HOSTS[utmSource.toLowerCase()];
if (fromUtm) {
return { name: fromUtm, via: 'utm_source' };
}
}
return null;
}
const match = detectAssistant();
const FLAG = 'ai_assistant_visit_sent';
if (match && !sessionStorage.getItem(FLAG)) {
sessionStorage.setItem(FLAG, '1');
gtag('event', 'ai_assistant_visit', {
assistant_name: match.name,
detection_method: match.via
});
}Three details in this code matter.
- The
try/catcharoundnew URL. An emptydocument.referreris an empty string, andnew URL('')throws. Without the guard, the script stops on every direct visit. - The
sessionStorageflag.document.referrerdoes not change when the visitor reloads the page, and it keeps the same value on a back-navigation. Without the flag, each reload sends another event.sessionStorageis cleared when the tab closes, which approximates a GA4 session. - The
detection_methodparameter. It lets you later measure how often the referrer was missing and the UTM fallback saved the visit.
The first page of the session is the only page that matters for attribution, so the flag is also a reasonable proxy for "landing page". If the visitor opens a second page in a new tab from the same assistant, the new tab has its own sessionStorage, and the event fires again. This is usually acceptable, but it can inflate counts slightly.
Option 2: Google Tag Manager
If your site uses GTM, you can avoid editing site code. The setup has four parts.
- Variable. Create a Custom JavaScript variable that returns the assistant name, using the same lookup logic as above. Return
undefinedwhen there is no match. - Trigger. Create a Page View trigger that fires only when that variable is not undefined. Use the condition "does not equal"
undefined, or return an empty string instead and test against that. - Tag. Create a GA4 Event tag with the event name
ai_assistant_visitand an event parameterassistant_nameset to the variable. Point it at your existing Google tag or measurement ID. - Once per session. In the tag's advanced settings, set Tag firing options to Once per page at minimum. For true once-per-session behaviour, write a first-party cookie or
sessionStorageflag in the variable, as in the gtag snippet.
Test in GTM Preview mode before publishing. Preview shows whether the trigger fired and what the variable returned for each page.
Make the parameter usable in GA4
Sending the event is not enough to report on it. GA4 collects assistant_name as a raw event parameter, but standard reports and explorations can only show it after you register it.
- Go to Admin > Data display > Custom definitions.
- Select Create custom dimension.
- Set Scope to Event, Dimension name to a readable label such as
Assistant name, and Event parameter toassistant_name. - Save. Repeat for
detection_methodif you want to report on it.
New custom dimensions can take up to a day to appear in reports. The event itself shows up in Realtime and DebugView straight away, even though the dimension is not yet reportable. The BigQuery export contains the raw parameter regardless of registration.
Optional: mark it as a key event
If you want to count AI-assisted visits as a goal, open Admin > Data display > Events and turn on Mark as key event for ai_assistant_visit. Do this only if the count is meaningful to you. A visit is not a conversion, and a key event inflates your conversion totals if you mix it with purchases or sign-ups.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| No events at all | `gtag` is not defined when the script runs, or the script is placed before the Google tag | Move it after the Google tag, or use GTM |
| Script stops on direct visits | `new URL('')` throws with no `try/catch` | Wrap URL parsing as shown |
| Duplicate events on reload | No session guard | Add the `sessionStorage` flag |
| Events arrive but `assistant_name` is missing in reports | Parameter not registered as a custom dimension | Register it under Custom definitions and wait for processing |
| `perplexity.ai` visits not matched | Host is `www.perplexity.ai` | Keep both hosts in the lookup |
| Event fires on pages reached from your own site | Your own domain is in the lookup list | Keep the list limited to assistant hosts |
| Counts differ from the channel group | Different definitions: the event is per tab and session guard, the channel is per GA4 session | Compare trends, not exact totals |
Verify before you trust it
Verification follows the same path as the earlier validation chapter, now applied to the event.
- Open DebugView by adding
debug_mode: trueto the event parameters for the test, or by using GTM Preview. - Visit your site from an assistant link if you can. Otherwise simulate it by opening a URL with
?utm_source=chatgpt.comappended. - Confirm that
ai_assistant_visitappears with the expectedassistant_name. - Reload the page and confirm that no second event appears.
A URL with a UTM parameter tests only the fallback path. The document.referrer path needs a real click from a page on an assistant host. If you cannot test one directly, serve a simple HTML page from a host listed in your lookup and click through from it.
What the event does not fix
The event reads exactly the signals that the channel group uses. It does not fill in the gaps from the "Direct and missing referrers" chapter.
- Visits from native mobile apps often arrive with no referrer. The code sees an empty string and sends nothing.
- Copy-pasted URLs carry no referrer and no UTM tag.
- Visitors who decline analytics consent send no event.
Treat the count as a lower bound, and report it that way.
Exercise
Your ai_assistant_visit event shows up in DebugView with the right assistant_name, but the Assistant name dimension is missing from your exploration three days later. Give the most likely cause and the fix. Also say whether the first three days of data can be recovered in the exploration.
Show answer
The event parameter assistant_name was never registered as an event-scoped custom dimension. Register it under Admin > Data display > Custom definitions with scope Event and event parameter assistant_name. Registration is not retroactive, so the first three days will not appear in the exploration. The raw parameter is still in the BigQuery export if the export was enabled, so you can analyse those days there.