技术求助:通过GTM存储首次访问完整Referer至Cookie并同步至CRM
Got it, let's break this down into actionable, reliable steps—this is a common lead tracking workflow I’ve set up many times before.
1. Core Cookie Writing Logic (Custom JavaScript)
First, we need a script that only writes the referrer cookie once (on the user’s first visit to any page) and never overwrites it. Here’s the code, with comments explaining each part:
function setFirstReferrerCookie() { // Check if the "first_referrer" cookie already exists const cookieExists = document.cookie.split(';').some(cookie => cookie.trim().startsWith('first_referrer=') ); // Only proceed if the cookie doesn't exist if (!cookieExists) { // Capture the referrer, default to "direct" if user landed directly (no referrer) const userReferrer = document.referrer || 'direct'; // Set cookie to expire in 1 year (adjust as needed) const expiryDate = new Date(); expiryDate.setFullYear(expiryDate.getFullYear() + 1); // Write the cookie with proper attributes (SameSite, path, expiry) document.cookie = `first_referrer=${encodeURIComponent(userReferrer)}; expires=${expiryDate.toUTCString()}; path=/; SameSite=Lax`; } } // Run the function immediately setFirstReferrerCookie();
Why this works:
- It checks for the cookie first, so subsequent page loads won’t overwrite the original referrer
- Handles direct visits (no referrer) by storing "direct"
- Uses
encodeURIComponentto safely handle special characters in referrer URLs - Sets
path=/so the cookie is accessible across your entire site
2. GTM Configuration Steps
Now let’s add this to GTM:
Step 1: Create a Custom HTML Tag
- In GTM, go to Tags > New > Custom HTML
- Paste the script above into the HTML field
- Under Triggering, select Page View - DOM Ready (this ensures the script runs early enough, but after the referrer is available)
Step 2: Create a Cookie Variable to Read the Value
- Go to Variables > User-Defined Variables > New > 1st Party Cookie
- Name it
first_referrer - In the Cookie Name field, enter
first_referrer - Save the variable
Step 3: Verify Triggering
The tag will run on every page load, but the script’s logic ensures it only writes the cookie once. No need for special triggers here— the self-contained check handles the "only once" requirement.
3. Populate the Form’s Hidden Field
Next, we need to fill your lead form’s hidden field with the cookie value when the form loads.
Custom Script for Hidden Field Population
Create another Custom HTML tag with this code:
function populateReferrerHiddenField() { // Get the cookie value from GTM's variable const referrerValue = {{first_referrer}}; // Target your hidden field (update the selector to match your form's field) const hiddenField = document.querySelector('input[name="first_referrer"]'); // Only populate if the field exists and we have a referrer value if (hiddenField && referrerValue) { hiddenField.value = decodeURIComponent(referrerValue); } } // Run the function populateReferrerHiddenField();
Trigger for This Tag
- If your form loads with the page: Use Page View - DOM Ready
- If your form is dynamically loaded (e.g., a modal that pops up later): Use Element Visibility trigger targeting the form container, or a Custom Event that fires when the form is rendered.
4. Sync to Your CRM
Once the hidden field is populated, syncing to your CRM is straightforward:
- In your CRM’s form settings (e.g., Salesforce, HubSpot, Marketo), map the hidden field’s name (
first_referrer) to a corresponding CRM property (e.g., "First Referrer URL"). - When the form is submitted, the CRM will automatically capture the value from the hidden field alongside other lead data.
5. Testing & Validation
Always test before publishing to production:
- Clear your browser cookies and visit your site for the first time. Check Chrome DevTools > Application > Cookies to confirm
first_referreris set. - Navigate to other pages—verify the cookie value doesn’t change.
- Load your lead form and inspect the hidden field (DevTools > Elements) to confirm it’s populated with the referrer value.
- Submit the form and check your CRM to ensure the value was captured correctly.
- Use GTM’s Preview Mode to verify tags are triggering as expected.
内容的提问来源于stack exchange,提问作者Sabeel

