Skip to content

Instantly share code, notes, and snippets.

@stylesuxx
Last active January 6, 2019 01:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stylesuxx/06f56763d1691d9efbcc07c99bacc0c3 to your computer and use it in GitHub Desktop.
Save stylesuxx/06f56763d1691d9efbcc07c99bacc0c3 to your computer and use it in GitHub Desktop.
Add and/or replace URL parameters in links
(function() {
this.Affiliate = function(options) {
this.settings = {
affiliates: [],
};
function extendDefaults(source, properties) {
for(var property in properties) {
if(properties.hasOwnProperty(property)) {
source[property] = properties[property];
}
}
return source;
}
this.settings = extendDefaults(this.settings, options);
}
Affiliate.prototype.replace = function() {
var links = document.getElementsByTagName("a");
for(var i = 0; i < links.length; i++) {
var link = links[i];
var href = link.href;
for(var j = 0; j < this.settings.domains.length; j++) {
var affiliate = this.settings.domains[j];
var params = affiliate.params;
var re = new RegExp("^(https?\:\/\/)(www\\.)?" + affiliate.domain + ".*");
var matches = href.match(re);
if(matches) {
var keys = Object.keys(params);
var usedParams = [];
if(href.indexOf("?") > -1) {
var currentUrl = href.split("?")[0];
var currentParams = href.split("?")[1].split("&");
href = currentUrl + "?";
for(var k = 0; k < currentParams.length; k++) {
var paramKey = currentParams[k].split("=")[0];
var paramValue = currentParams[k].split("=")[1];
if(keys.indexOf(paramKey) > -1) {
paramValue = params[paramKey];
}
href += paramKey + "=" + paramValue + "&";
usedParams.push(paramKey);
}
} else {
href += "?";
}
for(var l = 0; l < keys.length; l++) {
var key = keys[l];
if(usedParams.indexOf(key) < 0) {
var param = params[key];
href += keys[l] + "=" + param + "&";
}
}
href = href.slice(0, -1);
link.href = encodeURI(href);
}
}
}
}
}());
var affiliate = new Affiliate({
'domains': [
{
'domain': 'banggood.com',
'params': {
'p': 'p-param',
't': 't param'
},
},
{
'domain': 'gearbest.com',
'params': {
'p': 'p-param',
't': 't param'
},
},
],
});
affiliate.replace();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment