首页 > web前端 > js教程 > 正文

修复:持久化 UTM 代码导致链接出现多余问号的问题

DDD
发布: 2025-10-12 10:37:27
原创
591人浏览过

修复:持久化 utm 代码导致链接出现多余问号的问题

本文旨在解决在使用 JavaScript 持久化 UTM 参数时,即使 URL 中不存在 UTM 参数,链接仍然被错误地添加问号的问题。通过分析问题代码,找出导致错误的原因,并提供修改后的代码,确保只有在存在 UTM 参数时才添加问号,从而避免生成不必要的 URL 参数。

在使用 JavaScript 追踪用户来源,并持久化 UTM 参数(如 utm_source, utm_medium, utm_campaign 等)是非常常见的需求。然而,在实现过程中,可能会遇到一些问题,例如,即使URL中没有UTM参数,链接也会被错误地添加一个问号?。 这会导致URL看起来不美观,甚至可能影响某些网站的正常功能。本文将分析导致此问题的原因,并提供解决方案。

问题分析

问题出在 decorateUrl 函数中,该函数负责将 UTM 参数添加到 URL 中。原始代码无论 collectedQueryParams 是否为空,都会尝试添加 ? 或 & 符号。

function decorateUrl(urlToDecorate) {
    urlToDecorate = (urlToDecorate.indexOf('?') === -1) ? urlToDecorate + '?' : urlToDecorate + '&';
    var collectedQueryParams = [];
    for (var queryIndex = 0; queryIndex < queryParams.length; queryIndex++) {
        if (getQueryParam(queryParams[queryIndex])) {
            collectedQueryParams.push(queryParams[queryIndex] + '=' + getQueryParam(queryParams[queryIndex]))
        }
    }
    return urlToDecorate + collectedQueryParams.join('&');
}
登录后复制

这段代码的逻辑是:如果 urlToDecorate 中没有 ?,则添加 ?,否则添加 &。但是,它没有判断 collectedQueryParams 是否为空,也就是说,即使没有收集到任何 UTM 参数,也会添加 ? 或 &。

解决方案

为了解决这个问题,我们需要修改 decorateUrl 函数,使其在 collectedQueryParams 为空时,直接返回原始的 urlToDecorate。只有当 collectedQueryParams 不为空时,才添加 ? 或 & 符号。

修改后的 decorateUrl 函数如下:

function decorateUrl(urlToDecorate) {
    var collectedQueryParams = [];
    for (var queryIndex = 0; queryIndex < queryParams.length; queryIndex++) {
        if (getQueryParam(queryParams[queryIndex])) {
            collectedQueryParams.push(queryParams[queryIndex] + '=' + getQueryParam(queryParams[queryIndex]))
        }
    }

    if(collectedQueryParams.length === 0){
        return urlToDecorate;
    }

    //only add the ? if we have params AND if there isn't already one
    urlToDecorate = (urlToDecorate.indexOf('?') === -1) ? urlToDecorate + '?' : urlToDecorate + '&';
    return urlToDecorate + collectedQueryParams.join('&');
}
登录后复制

在这个修改后的版本中,我们首先检查 collectedQueryParams 的长度。如果长度为 0,说明没有收集到任何 UTM 参数,此时直接返回原始的 urlToDecorate,避免添加多余的 ? 符号。

完整代码示例

下面是包含修改后的 decorateUrl 函数的完整代码示例:

<script>
(function() {
    var domainsToDecorate = [
            'example.com'
        ],
        queryParams = [
            'utm_medium', //add or remove query parameters you want to transfer
            'utm_source',
            'utm_campaign',
            'utm_content',
            'utm_term'
        ]
    // do not edit anything below this line
    var links = document.querySelectorAll('a'); 

  // check if links contain domain from the domainsToDecorate array and then decorates
    for (var linkIndex = 0; linkIndex < links.length; linkIndex++) {
        for (var domainIndex = 0; domainIndex < domainsToDecorate.length; domainIndex++) { 
            if (links[linkIndex].href.indexOf(domainsToDecorate[domainIndex]) > -1 && links[linkIndex].href.indexOf("#") === -1) {
                links[linkIndex].href = decorateUrl(links[linkIndex].href);
            }
        }
    }
  // decorates the URL with query params
    function decorateUrl(urlToDecorate) {
        var collectedQueryParams = [];
        for (var queryIndex = 0; queryIndex < queryParams.length; queryIndex++) {
            if (getQueryParam(queryParams[queryIndex])) {
                collectedQueryParams.push(queryParams[queryIndex] + '=' + getQueryParam(queryParams[queryIndex]))
            }
        }

        if(collectedQueryParams.length === 0){
            return urlToDecorate;
        }

        //only add the ? if we have params AND if there isn't already one
        urlToDecorate = (urlToDecorate.indexOf('?') === -1) ? urlToDecorate + '?' : urlToDecorate + '&';
        return urlToDecorate + collectedQueryParams.join('&');
    }


    // a function that retrieves the value of a query parameter
    function getQueryParam(name) {
        if (name = (new RegExp('[?&]' + encodeURIComponent(name) + '=([^&]*)')).exec(window.location.search))
            return decodeURIComponent(name[1]);
    }

})();
</script>
登录后复制

注意事项

  • 确保 domainsToDecorate 数组包含你想要追踪的域名。
  • queryParams 数组包含你想要持久化的 UTM 参数。
  • 在部署代码之前,务必进行充分的测试,确保其在各种场景下都能正常工作。

总结

通过修改 decorateUrl 函数,我们可以避免在 URL 中添加多余的 ? 符号,从而使 URL 更加清晰和易于管理。在实际应用中,需要根据具体的需求进行适当的调整和优化,以达到最佳的效果。

以上就是修复:持久化 UTM 代码导致链接出现多余问号的问题的详细内容,更多请关注php中文网其它相关文章!

相关标签:
最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号