Skip to content

Instantly share code, notes, and snippets.

@BartVB
Created September 27, 2017 13:33
Show Gist options
  • Save BartVB/9e26dd0097770872537810229510ff56 to your computer and use it in GitHub Desktop.
Save BartVB/9e26dd0097770872537810229510ff56 to your computer and use it in GitHub Desktop.
// Store ad tags in localStorage to enable reporting bad ads
// TODO: This doesn't work if multiple ads are shown in one placement with googletag.pubads().refresh()
googletag.pubads().addEventListener('slotRenderEnded', function (event) {
if (typeof(localStorage) !== 'object') console.log('fail');
if (event.slot.getResponseInformation() === null) return;
var slotAdUnitPath = event.slot.getAdUnitPath();
gpt_placements[slotAdUnitPath] = {};
gpt_placements[slotAdUnitPath]['dfp'] = event.slot.getResponseInformation();
gpt_placements[slotAdUnitPath]['dfp']['contentUrl'] = event.slot.getContentUrl();
gpt_placements[slotAdUnitPath]['dfp']['queryId'] = event.slot.getEscapedQemQueryId();
var adId = event.slot.getTargeting('hb_adid')[0];
if (adId) {
gpt_placements[slotAdUnitPath]['pbjs'] = pbjs.getAllWinningBids().filter(function (bid) {
return bid.adId === adId;
});
}
if (gpt_placements[slotAdUnitPath]['dfp']) {
try {
localStorage.setItem("pbad_" + window.performance.timing.navigationStart, JSON.stringify(gpt_placements));
// Only store 20 items
if (Object.keys(gpt_placements).length === 1) { // Only needs to run once
var storageKeys = Object.keys(localStorage).sort().filter(function (key) {
return key.substring(0, 5) === "pbad_";
});
while (storageKeys.length > 20) {
localStorage.removeItem(storageKeys.shift());
}
}
} catch (e) {
console.log("Unable to save in LocalStorage");
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment