问题
I looked at the Google Publisher Tag reference and decided that I could add some events to my ad slots. It works great if I have defined only one slot. If I add more slots, the events keep repeating on my console number of times I have slots.
So, if I do something like this:
<script type='text/javascript'>
googletag.cmd.push(function() {
var slot1 = googletag.defineSlot('/123456/leadeboard', [[728, 90]], 'div-gpt-ad-123456789-0').addService(googletag.pubads());
var slot2 = googletag.defineSlot('/123456/leadeboard', [[728, 90]], 'div-gpt-ad-123456789-0').addService(googletag.pubads());
var slot3 = googletag.defineSlot('/123456/leadeboard', [[728, 90]], 'div-gpt-ad-123456789-0').addService(googletag.pubads());
googletag.pubads().enableSingleRequest();
googletag.pubads().addEventListener('slotRenderEnded', function(event) {
console.log('Slot has been rendered:');
});
googletag.enableServices();
});
</script>
My console.log would be 3x "Slot has been rendered:". If I remove two of the .addService from the defineSlot part, it only console.logs it once, but then the ad is not rendered.
Is there a way how to remove extra logging without breaking everything else? It can get extremely messy after a while.
Thanks!
回答1:
Nastasja,
The reason the output repeats three times is the event handler that you registered listens for the 'slotRenderEnded' event, which happens every time a slot renders. Since your example has three slots, the event will fire three times. You can see which slot triggers the callback by inspecting the event object that is passed in.
googletag.pubads().addEventListener('slotRenderEnded', function(event) {
console.log('Slot has been rendered:');
console.log(event); //inspect event
console.log(event.slot); //inspect slot
});
Even though the the event first three times, you can add slot based logic by comparing the slots in the event like this:
var slot1 = googletag.defineSlot('/123456/leadeboard', [[728, 90]], 'div-gpt-ad-123456789-0').addService(googletag.pubads());
googletag.pubads().addEventListener('slotRenderEnded', function(event) {
if(slot1 === event.slot){
console.log('slot1 has been rendered');
}
});
You can read more in the GPT documentation
来源:https://stackoverflow.com/questions/40154738/google-publisher-tag-registering-to-events