{"id":24078124,"url":"https://github.com/melogabriel/persist-utm-parameters-gtm","last_synced_at":"2026-04-14T07:33:19.199Z","repository":{"id":266317001,"uuid":"898014096","full_name":"melogabriel/persist-utm-parameters-gtm","owner":"melogabriel","description":"Persist UTM parameters between pages with Google Tag Manager (GTM)","archived":false,"fork":false,"pushed_at":"2025-04-29T15:59:37.000Z","size":14,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-04-29T16:49:53.503Z","etag":null,"topics":["analytics-tracking","google-tag-manager","gtm","javascript","utm-parameters"],"latest_commit_sha":null,"homepage":"https://melogabriel.github.io/persist-utm-parameters-gtm/","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/melogabriel.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2024-12-03T16:27:46.000Z","updated_at":"2025-04-29T16:02:32.000Z","dependencies_parsed_at":"2024-12-03T17:41:37.776Z","dependency_job_id":"149f2561-4e18-4890-8fea-d5118b3691ca","html_url":"https://github.com/melogabriel/persist-utm-parameters-gtm","commit_stats":null,"previous_names":["melogabriel/persist-utm-parameters-gtm"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/melogabriel/persist-utm-parameters-gtm","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/melogabriel%2Fpersist-utm-parameters-gtm","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/melogabriel%2Fpersist-utm-parameters-gtm/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/melogabriel%2Fpersist-utm-parameters-gtm/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/melogabriel%2Fpersist-utm-parameters-gtm/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/melogabriel","download_url":"https://codeload.github.com/melogabriel/persist-utm-parameters-gtm/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/melogabriel%2Fpersist-utm-parameters-gtm/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31786929,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-14T02:24:21.117Z","status":"ssl_error","status_checked_at":"2026-04-14T02:24:20.627Z","response_time":153,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["analytics-tracking","google-tag-manager","gtm","javascript","utm-parameters"],"created_at":"2025-01-09T21:01:19.280Z","updated_at":"2026-04-14T07:33:19.193Z","avatar_url":"https://github.com/melogabriel.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003cdiv align=\"center\"\u003e\n  \u003cimg src=\"https://img.shields.io/badge/Google%20Tag%20Manager-246FDB.svg?style=for-the-badge\u0026logo=Google-Tag-Manager\u0026logoColor=white\" alt=\"Google Tag Manager\" /\u003e\n  \u003cimg src=\"https://img.shields.io/badge/JavaScript-F7DF1E?style=for-the-badge\u0026logo=javascript\u0026logoColor=black\" alt=\"JavaScript\" /\u003e\n\u003c/div\u003e\n\n# Persist UTM Parameters with GTM\n\n\n\n---\nTo transfer UTM parameters, meaning to retain them across different pages and even sessions on your website, you can utilize cookies or local storage. This allows you to track the origin of a user's traffic even if they navigate to different parts of your site or revisit it later. You can achieve this using tools like Google Tag Manager (GTM) and custom HTML scripts.\n\n---\n\n## Features\n\n- Retrieves UTM parameters from the URL query string.\n- Stores UTM parameters in `sessionStorage` to persist them across pages.\n- Restores and appends UTM parameters to the URL if they are missing.\n- Handles spaces in UTM parameters by encoding them as `+` in the query string.\n- Ensures compatibility with URL encoding standards.\n\n---\n\n## Installation\n\nThis script can be integrated into a Google Tag Manager (GTM) custom HTML tag for easier deployment across your website. To use this with GTM:\n\n1. Create a new tag in GTM.\n2. Select \"Custom HTML\" as the tag type.\n3. Paste the script into the HTML field.\n   ```javascript\n   \u003cscript\u003e\n   (function() {\n    // Function to get URL parameters\n    function getUrlParams() {\n      var params = {};\n      var queryString = window.location.search.substring(1);\n      if (queryString) {\n        var pairs = queryString.split('\u0026');\n        for (var i = 0; i \u003c pairs.length; i++) {\n          var pair = pairs[i].split('=');\n          var key = decodeURIComponent(pair[0]);\n          var value = pair[1] ? decodeURIComponent(pair[1].replace(/\\+/g, ' ')) : ''; // Handle + as space\n          params[key] = value;\n        }\n      }\n      return params;\n    }\n\n    // Function to set URL parameters with `+` for spaces\n    function setUrlParams(params) {\n      var baseUrl = window.location.protocol + \"//\" + window.location.host + window.location.pathname;\n      var newUrl = baseUrl + '?' + Object.keys(params).map(function(key) {\n        return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]).replace(/%20/g, '+'); // Replace %20 with +\n      }).join('\u0026');\n      window.history.replaceState({ path: newUrl }, '', newUrl);\n    }\n\n    // Get current URL parameters\n    var params = getUrlParams();\n\n    // Check for UTM parameters and persist them if they exist\n    var utmParams = ['utm_source',\n                     'utm_medium',\n                     'utm_campaign',\n                     'utm_term',\n                     'utm_content',\n                     'fbclid',\n                     'gclid'];\n    var hasUtmParams = utmParams.some(function(param) {\n      return params[param];\n    });\n\n    if (hasUtmParams) {\n      // Store UTM parameters in sessionStorage\n      sessionStorage.setItem('utmParams', JSON.stringify(params));\n    } else {\n      // Retrieve stored UTM parameters if available\n      var storedParams = sessionStorage.getItem('utmParams');\n      if (storedParams) {\n        var parsedParams = JSON.parse(storedParams);\n        Object.assign(params, parsedParams);\n        setUrlParams(params);\n      }\n    }\n   })();\n   \u003c/script\u003e\n   ```\n   \n5. Set the tag to trigger on \"All Pages\" or specific pages where UTM persistence is required.\n6. Publish the changes in GTM.\n\nOR\n\n1. Copy the script to your project.\n2. Include the script in the `\u003chead\u003e` or `\u003cbody\u003e` section of your HTML file:\n3. Test the script by navigating to a page with UTM parameters in the URL.\n\n---\n## Code Explanation\n\n### Functions\n\n1. **`getUrlParams()`**\n   - Parses the URL query string to extract parameters as key-value pairs.\n   - Replaces `+` with spaces before decoding the parameters.\n\n   ```javascript\n   function getUrlParams() {\n     var params = {};\n     var queryString = window.location.search.substring(1);\n     if (queryString) {\n       var pairs = queryString.split('\u0026');\n       for (var i = 0; i \u003c pairs.length; i++) {\n         var pair = pairs[i].split('=');\n         var key = decodeURIComponent(pair[0]);\n         var value = pair[1] ? decodeURIComponent(pair[1].replace(/\\+/g, ' ')) : '';\n         params[key] = value;\n       }\n     }\n     return params;\n   }\n   ```\n\n2. **`setUrlParams(params)`**\n   - Reconstructs the URL with the provided parameters.\n   - Encodes parameter values and replaces spaces (`%20`) with `+` for readability and compatibility.\n\n   ```javascript\n   function setUrlParams(params) {\n     var baseUrl = window.location.protocol + \"//\" + window.location.host + window.location.pathname;\n     var newUrl = baseUrl + '?' + Object.keys(params).map(function(key) {\n       return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]).replace(/%20/g, '+');\n     }).join('\u0026');\n     window.history.replaceState({ path: newUrl }, '', newUrl);\n   }\n   ```\n\n3. **Main Script Logic**\n   - Retrieves UTM parameters using `getUrlParams`.\n   - Checks if UTM parameters are present and stores them in `sessionStorage`.\n   - If no UTM parameters are found in the current URL, retrieves them from `sessionStorage` and appends them to the URL.\n\n   ```javascript\n   var params = getUrlParams();\n\n   var utmParams = ['utm_source',\n                     'utm_medium',\n                     'utm_campaign',\n                     'utm_term',\n                     'utm_content',\n                     'fbclid',\n                     'gclid'];\n   var hasUtmParams = utmParams.some(function(param) {\n     return params[param];\n   });\n\n   if (hasUtmParams) {\n     sessionStorage.setItem('utmParams', JSON.stringify(params));\n   } else {\n     var storedParams = sessionStorage.getItem('utmParams');\n     if (storedParams) {\n       var parsedParams = JSON.parse(storedParams);\n       Object.assign(params, parsedParams);\n       setUrlParams(params);\n     }\n   }\n   ```\n\n---\n\n## How It Works\n\n1. A user lands on your website with UTM parameters, e.g., `https://example.com/?utm_source=google\u0026utm_medium=cpc`.\n2. The script stores these parameters in `sessionStorage`.\n3. When the user navigates to another page, the script:\n   - Checks if UTM parameters are in the URL.\n   - If not, appends the stored UTM parameters to the URL.\n4. Spaces in UTM parameter values are displayed as `+` for compatibility.\n\n---\n\n## Notes\n\n- The script uses `sessionStorage`, so parameters persist only during the browser session.\n- To extend persistence beyond a session, consider using `localStorage` instead of `sessionStorage`.\n- Ensure the script is included on all pages where UTM parameter persistence is required.\n\n---\n\n## License\n\nThis project is open-source and available under the MIT License. Feel free to use and modify it as needed.\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmelogabriel%2Fpersist-utm-parameters-gtm","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmelogabriel%2Fpersist-utm-parameters-gtm","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmelogabriel%2Fpersist-utm-parameters-gtm/lists"}