给你的文章外链自动添加 utm_source 参数

为了给文章中的外链增加相应的回流,可以考虑给所有站外链接增加 utm_source 参数。

什么是 utm_source ?流量渠道标记(UTM) – 知乎 (zhihu.com)

以下 JavaScript 代码尽可能详尽的增加了注释与异常处理,将代码添加到网页 的 header 或者 footer 标签中即可。

function addUtmSourceToLinks() {
  // 获取当前浏览器地址的 host
  const currentHost = window.location.hostname;
  // 获取页面中所有的 <a> 标签
  const links = document.querySelectorAll('a');

  // 遍历每一个 <a> 标签
  links.forEach(link => {
    // 确保 link 不是 null
    if (link) {
      // 获取当前链接的 href 属性
      const href = link.getAttribute('href');

      // 确保 href 不是 null
      if (href && href.includes('://')) {
        // 当链接域名与当前页域名不一致时添加
        const herfHost = new URL(href).hostname;
        if (herfHost && herfHost !== currentHost) {
          // 分离 URL 的 hash 部分以便后续重新附加
          const [urlWithoutHash, hash] = href.split('#');
          const urlWithQuery = urlWithoutHash.includes('?');

          // 检查 URL 是否已经包含 utm_source 参数
          const utmSourceRegex = /(utm_source=)([^&#]*)/;
          let hasEmptyUtmSource = false;
          if (urlWithQuery) {
            const match = urlWithoutHash.match(utmSourceRegex);
            if (match && match[2] === '') {
              hasEmptyUtmSource = true;
            }
          }

          // 如果 URL 包含空的 utm_source 参数或者不包含 utm_source 参数
          if (hasEmptyUtmSource || !utmSourceRegex.test(urlWithoutHash)) {
            // 构造新的 URL,如果 URL 已经有查询参数,则在 & 符号后添加 utm_source 参数
            // 否则,在 URL 末尾添加 ? 符号和 utm_source 参数
            const utmSourceValue = currentHost; // 替换为你想要设置的 utm_source 参数值
            let newUrlWithoutHash = urlWithoutHash;
            if (urlWithQuery) {
              // 如果 URL 已经包含 utm_source 参数但值为空,移除它
              if (hasEmptyUtmSource) {
                newUrlWithoutHash = newUrlWithoutHash.replace(utmSourceRegex, '$1$2');
              }
              newUrlWithoutHash += `&utm_source=${encodeURIComponent(utmSourceValue)}`;
            } else {
              newUrlWithoutHash += `?utm_source=${encodeURIComponent(utmSourceValue)}`;
            }

            // 重新附加原始 URL 的 hash 部分
            const newUrl = newUrlWithoutHash + (hash ? `#${hash}` : '');

            // 更新链接的 href 属性
            link.setAttribute('href', newUrl);
          }
        }
      }
    }
  });
}

// 确保 DOM 完全加载后执行 addUtmSourceToLinks 函数
document.addEventListener('DOMContentLoaded', (event) => {
  addUtmSourceToLinks();
});

当然你可以通过代码参考,修改链接的任意属性和参数

Author: thinkwei

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注