You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Tag Manager:将第一方Cookie中click_id注入链接占位符的疑问

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:

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.hostname check ensures we only modify links going to external domains. Remove this if you want to target internal links too.
  • Fallback Logic: If the click_id cookie 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_campaign parameter if click_id is missing, update the newUrl line 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.hostname check.

内容的提问来源于stack exchange,提问作者Laurent Malka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:19:26