Skip to content

Instantly share code, notes, and snippets.

@PaulKinlan
Created March 5, 2015 16:29
Show Gist options
  • Save PaulKinlan/5bc2d380b67071ccaea0 to your computer and use it in GitHub Desktop.
Save PaulKinlan/5bc2d380b67071ccaea0 to your computer and use it in GitHub Desktop.
Detect unknown content injection
var detectInjection = function(knownHostsArray) {
var requests = window.performance.getEntriesByType("resource");
var unknownHosts = [];
var knownHosts = {};
var foundHosts = {};
for (var knownHost in knownHostsArray) {
knownHosts[knownHostsArray[knownHost]] = true;
}
for(var requestIdx = 0; requestIdx < requests.length; requestIdx++) {
var request = requests[requestIdx];
var url = new URL(request.name);
var host = url.host;
// Aggregate all the requests from a host
if(host in foundHosts) {
foundHosts[host].push(request);
}
else {
foundHosts[host] = new Array(request);
}
}
for(var foundHost in foundHosts) {
// If an unknown host is found, add it to a list.
if(!(foundHost in knownHosts)) {
unknownHosts.push(foundHost);
}
}
return unknownHosts;
};
window.addEventListener("load", function() {
var scripts = detectInjection(["paul.kinlan.me", "ssl.google-analytics.com", "www.google-analytics.com", "disqus.com", "paulkinlan.disqus.com"]);
if(!!scripts == true && scripts.length > 0) {
for(var scriptsIdx = 0; scriptsIdx < scripts.length; scriptsIdx++) {
var scr = scripts[scriptsIdx];
ga('send', 'event', 'load', 'unknown-host', scr, {'nonInteraction': 1});
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment