Created
September 21, 2018 22:40
-
-
Save keithws/ee00d3aacb40835e81005ff76cf87ba4 to your computer and use it in GitHub Desktop.
Get IP address and add it to the Google Tag Manager data layer. Uses the free ipify.org service and intelligent caching to minimize requests.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
/* | |
* get ip address and add it to the GTM data layer | |
* uses the free ipify.org service | |
* and intelligent caching to minimize requests | |
*/ | |
// mark the start of the script loading | |
window.dataLayer = window.dataLayer || []; | |
window.dataLayer.push({ | |
"event": "ipify.js", | |
"ipify.start": (new Date()).getTime() | |
}); | |
(function () { | |
"use strict"; | |
var ip, newNode, referenceNode; | |
// helper function to execute once we have the IP address | |
function putIPinDataLayer (ip) { | |
window.dataLayer.push({ | |
"event": "ipify.load", | |
"ipify.ip": ip | |
}); | |
} | |
if (sessionStorage) { | |
ip = sessionStorage.getItem("ipify.ip"); | |
} | |
if (ip) { | |
// use IP address retrieved from session cache | |
putIPinDataLayer(ip); | |
} else { | |
// use ipify.org to get IP address | |
// listen for when the IP address has been loaded by ipfiy | |
window.ipifyCallback = function ipifyCallback (json) { | |
if (sessionStorage) { | |
sessionStorage.setItem("ipify.ip", json.ip); | |
} | |
putIPinDataLayer(json.ip); | |
}; | |
// inject the script from ipify.org | |
newNode = document.createElement("script"); | |
newNode.async = true; | |
newNode.src = "https://api.ipify.org?format=jsonp&callback=ipifyCallback"; | |
referenceNode = document.getElementsByTagName("script")[0]; | |
referenceNode.parentNode.insertBefore(newNode, referenceNode); | |
} | |
}()); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment