Skip to content

Instantly share code, notes, and snippets.

@RichardDillman
Last active June 9, 2018 13:03
Show Gist options
  • Save RichardDillman/317e4e55047eaf4e51cfeb1ea75e089f to your computer and use it in GitHub Desktop.
Save RichardDillman/317e4e55047eaf4e51cfeb1ea75e089f to your computer and use it in GitHub Desktop.
Returns an array of ad requests.
/**
* Returns an array of ad requests. Requires modern browsers.
* [{
* correlator: '1978064853149162',
* pageTargeting: {
* key1: 'val1',
* key2: 'val2',
* },
* slots: [{
* sizes: [
* '300X250',
* '300X600'
* ],
* targeting: {
* key1: 'val1',
* key2: 'val2',
* }
* }]
* }]
*/
function getAdRequests() {
function getUrlParams(search) {
let hashes = search.name.slice(search.name.indexOf('?') + 1)
.split('&').filter(item => {
return /^correlator|^prev_iu_szs|^prev_scp|^cust_params/.test(item);
});
let params = {}
hashes.map(hash => {
let [key, val] = hash.split('=')
params[key] = decodeURIComponent(val)
})
return params
}
function arrayToObject(obj, entry) {
obj[entry[0]] = entry[1];
return obj;
}
return performance.getEntries()
.filter(entry => {
return /pubads.g.doubleclick.net\/gampad\/ads/.test(entry.name);
})
.map(getUrlParams)
.map(entry => {
const slots = [];
entry.prev_iu_szs.split(',').forEach(slot => {
slots.push({sizes: slot.split('|')});
})
return Object.assign(entry, {slots: slots });
})
.map(entry => {
const slots = [];
(entry.prev_scp.split('|') || []).forEach(slot => {
slot = (slot.split('&') || []).map(el => el.split('='))
.reduce(arrayToObject, {}),
slots.push(slot);
});
entry.slots.forEach((slot, i) => {
slot.targeting = slots[i];
});
return {
correlator: entry.correlator,
pageTargeting: (entry.cust_params && entry.cust_params.split('&') || [])
.map(entry => entry.split('='))
.reduce(arrayToObject, {}),
slots: entry.slots
};
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment