Skip to content

Instantly share code, notes, and snippets.

@beijaflor
Forked from PaulKinlan/detect.js
Created April 29, 2016 00:40
Show Gist options
  • Save beijaflor/4a5b0ca146414b172c1b065e06f0c69b to your computer and use it in GitHub Desktop.
Save beijaflor/4a5b0ca146414b172c1b065e06f0c69b 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