Advertisement
prabapro

Decorate Link with Query String

Feb 20th, 2023 (edited)
616
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 1.28 KB | None | 0 0
  1. <script>
  2.   (function() {
  3.     // List of domains to decorate (without https or trailing slash)
  4.     var domainsToDecorate = ['booker.com', 'somedomain.com'];
  5.    
  6.     // Value to be set as linker param
  7.     var referrerDomain = 'ref-domain=' + document.location.hostname + '-praba-test';
  8.    
  9.     // Get all the links
  10.     var links = document.querySelectorAll('a');
  11.    
  12.     // Filter the required domains
  13.     for (var linkIndex = 0; linkIndex < links.length; linkIndex++) {
  14.      for (var domainIndex = 0; domainIndex < domainsToDecorate.length; domainIndex++) {
  15.        if (links[linkIndex].href.indexOf(domainsToDecorate[domainIndex]) > -1 && links[linkIndex].href.indexOf("#") === -1) {
  16.          links[linkIndex].href = decorateUrl(links[linkIndex].href);
  17.         }
  18.       }
  19.     }
  20.    
  21.     // decorates the URL with query params
  22.     function decorateUrl(urlToDecorate) {
  23.       urlToDecorate = (urlToDecorate.indexOf('?') === -1) ? urlToDecorate + '?' : urlToDecorate + '&';
  24.       return urlToDecorate + '&' + referrerDomain;
  25.     }
  26.    
  27.     // Append value as query parameter
  28.     function getQueryParam(name) {
  29.       if (name = (new RegExp('[?&]' + encodeURIComponent(name) + '=([^&]*)')).exec(window.location.search)) return decodeURIComponent(name[1]);
  30.     }
  31.   })();
  32. </script>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement