Google Tag Manager:将第一方Cookie中click_id注入链接占位符的疑问
Solution for Replacing {click_id} Placeholder in Outbound Links on Click
Got it, here's a reliable approach to inject your first-party cookie's click_id value into outbound links with the {click_id} placeholder, right when the user clicks the link:
Step 1: Helper Function to Retrieve Cookie Values
First, we need a simple way to pull the click_id from your site's cookies:
function getCookie(name) { const value = `; ${document.cookie}`; const parts = value.split(`; ${name}=`); if (parts.length === 2) return parts.pop().split(';').shift(); }
This function parses the document's cookie string and extracts the exact value for the specified cookie name.
Step 2: Listen for Clicks & Replace Placeholder
We'll attach a click listener to the entire document (this works even for links loaded dynamically after the page initializes) to intercept outbound link clicks:
document.addEventListener('click', function(e) { const link = e.target.closest('a'); // Exit early if we didn't click a link, or it's an internal link if (!link || link.hostname === window.location.hostname) return; // Check if the link contains our placeholder if (link.href.includes('{click_id}')) { e.preventDefault(); // Stop the default link navigation // Grab the click_id from cookies const clickId = getCookie('click_id'); // Replace the placeholder – use the cookie value if it exists, else keep the original URL const newUrl = clickId ? link.href.replace('{click_id}', clickId) : link.href; // Navigate to the modified URL window.location.href = newUrl; } });
Key Details Breakdown:
closest('a'): Ensures we target the actual link element even if the user clicks a child element (like an icon or text span) inside the link.- Outbound Link Filter: The
link.hostname !== window.location.hostnamecheck ensures we only modify links going to external domains. Remove this if you want to target internal links too. - Fallback Logic: If the
click_idcookie is missing, we just use the original URL (you could adjust this to remove the placeholder parameter entirely if needed). - Dynamic Link Support: Listening to the document instead of individual links means this works for links added later via AJAX or client-side rendering.
Quick Customizations:
- To remove the entire
utm_campaignparameter ifclick_idis missing, update thenewUrlline to:const newUrl = clickId ? link.href.replace('{click_id}', clickId) : link.href.replace(/[?&]utm_campaign={click_id}/, ''); - To target all links (not just outbound), delete the
link.hostname === window.location.hostnamecheck.
内容的提问来源于stack exchange,提问作者Laurent Malka
相关产品推荐
相关产品推荐

