Skip to content

Instantly share code, notes, and snippets.

@girlcheese
Last active June 12, 2020 03:31
Show Gist options
  • Save girlcheese/29acea17ba606b01153c to your computer and use it in GitHub Desktop.
Save girlcheese/29acea17ba606b01153c to your computer and use it in GitHub Desktop.
slotRenderEnded listener event (DFP)
googletag.pubads().addEventListener("slotRenderEnded", function(event) {
//console.log("googletag slotRenderEnded", event.slot.b.f);
var containerId = "";
// WARN: Fragile access of private object within DFP Slot Object returned with the event
// It's the only way to get access to the id of the DOM element attached to the slot
// FIXME: Ideally we need to contact Google and request a public API method to return the id
if (typeof event.slot !== "undefined") {
if (typeof event.slot.b !== "undefined") {
if (typeof event.slot.b.f !== "undefined") {
containerId = "#" + event.slot.b.f;
}
}
}
if (containerId !== "") {
if (event.isEmpty === false) {
// not an entirely safe access of private areas in the GPT Slot object
// [Obj].b.d is a volatile reference
//containerId = "#" + event.slot.b.d;
$(containerId).closest('.media')
.addClass('has-ad ' + $(containerId).data('adunit'))
.trigger("sponsorship:has-ad");
}
// Fired whether or not the slot has an ad,
// once render loop is completed
$(containerId).trigger("sponsorship:rendered");
} else {
//console.warn("Sponsorship: Failure to detect ad unit ID from Google Slot object");
}
});
@girlcheese
Copy link
Author

Lines 9-15 should use a more robust getter but none is available.

@gbelken
Copy link

gbelken commented Oct 5, 2016

Hi,

Just curious are you using the code above in production? I had the hope DFP would return the containerId but instead just seem to find it buried deep into the return object. Have you had any issues using the code above?

@krcrawford
Copy link

If I understand this correctly, why not just use the pubads slot api?

event.slot.getSlotElementId();

@jeffersonRibeiro
Copy link

Line 9-15 could be something like:

var containerId = ( ( event.slot || {} ).b || {} ).f;

if(!!containerId) {
    containerId = `#${containerId}`;
    ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment