Skip to content

Instantly share code, notes, and snippets.

@joshuatz
Created April 1, 2019 06:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshuatz/1b40e8b81f780707c2298ad2d4f8ee0b to your computer and use it in GitHub Desktop.
Save joshuatz/1b40e8b81f780707c2298ad2d4f8ee0b to your computer and use it in GitHub Desktop.
(function(){
function httpFetchVanilla(url,method,callback,OPT_failCallback){method="string"==typeof method&&""!==method?method:"GET",callback="function"==typeof callback?callback:function(){},failCallback="function"==typeof OPT_failCallback?OPT_failCallback:function(){console.warn("httpFetchVanilla failed")};var t=new XMLHttpRequest;t.onreadystatechange=function(){4==t.readyState&&(200==t.status?callback(t.responseText):failCallback())},t.open(method,url,!0),t.send()}
function setCookie(name, value, days) {
var d = new Date;
d.setTime(d.getTime() + 24*60*60*1000*days);
document.cookie = name + "=" + value + ";path=/;expires=" + d.toGMTString();
}
function getCookie(name) {
var v = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
return v ? v[2] : null;
}
window.conditionallyLoadTags = function(conditions,nonEmployeeCb,employeeCb){
nonEmployeeCb = typeof(nonEmployeeCb)==='function' ? nonEmployeeCb : function(){};
employeeCb = typeof(employeeCb)==='function' ? employeeCb : function(){};
var employee = false;
var hasIpFilter = false;
if (typeof(conditions)==='object' && conditions!==null){
if (typeof(conditions['cookie'])==='object'){
// Test for cookie val match
if (getCookie(conditions.cookie.name) == conditions.cookie.value.toString()){
employee = true;
}
}
if (!employee && typeof(conditions['ipAddresses'])==='object'){
hasIpFilter = true;
var ipFilter = conditions.ipAddresses;
// Get actual IP of client
httpFetchVanilla('https://api.ipify.org/?format=json','GET',function(res){
try {
var ipMatched = false;
var ip = JSON.parse(res)['ip'];
// Test IP
if (Array.isArray(ipFilter)){
// Assume array of IP strings
if (ipFilter.indexOf(ip)!==-1){
ipMatched = true;
}
}
else {
// Assume regex
if (ipFilter.test(ip)){
ipMatched = true;
}
}
ipMatched === true ? employeeCb() : nonEmployeeCb();
}
catch (e){
// Could not parse JSON, assume not an employee
nonEmployeeCb();
}
},function(){
// Something went wrong. Assume not an employee
nonEmployeeCb();
});
}
}
if (!hasIpFilter){
employee===true ? employeeCb() : nonEmployeeCb();
}
};
})();
// Example:
conditionallyLoadTags({
'ipAddresses' : ['216.3.128.12'],
'cookie' : {
'name' : 'isInternalEmployee',
'value' : 'true'
}
},function(){
console.log('You are not an employee. Firing tags.');
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config','UA-12345678-01');
},function(){
console.log('EMPLOYEE RECOGNIZED!!! Not firing tags.');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment