Javascript DFP 渲染后回调
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11218194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
DFP post-rendering callback
提问by Sp4cecat
I need to trigger some JavaScript afterDFP has finished rendering all the ads on the page - or at least when it has triggered collapseEmptyDivs(which hides ad units that contain no line items).
在DFP 完成呈现页面上的所有广告之后,我需要触发一些 JavaScript - 或者至少在它触发了collapseEmptyDivs(隐藏不包含订单项的广告单元)时触发。
Is anyone aware of a way to get DFP to trigger a callback after either of these events?
有没有人知道在这些事件中的任何一个之后让 DFP 触发回调的方法?
回答by z12345
The GPT API now has a callback that is triggered after each slot is filled.
GPT API 现在有一个回调,在每个槽被填充后触发。
For example:
例如:
googletag.pubads().addEventListener('slotRenderEnded', function(event) {
console.log('Creative with id: ' + event.creativeId +
' is rendered to slot of size: ' + event.size[0] + 'x' + event.size[1]);
});
See https://developers.google.com/doubleclick-gpt/reference#googletag.events.SlotRenderEndedEvent
请参阅https://developers.google.com/doubleclick-gpt/reference#googletag.events.SlotRenderEndedEvent
回答by Countis
I hacked googletag's debug_log.log function and pushed it through jQuery to fire events on a lot of DFP's actions. The hack does require jQuery.
我破解了 googletag 的 debug_log.log 函数,并通过 jQuery 推送它来触发许多 DFP 操作的事件。黑客确实需要jQuery。
https://github.com/mcountis/dfp-events
https://github.com/mcountis/dfp-events
- gpt-google_js_loaded
- gpt-gpt_fetch
- gpt-gpt_fetched
- gpt-page_load_complete
- gpt-queue_start
- gpt-service_add_slot
- gpt-service_add_targeting
- gpt-service_collapse_containers_enable
- gpt-service_create
- gpt-service_single_request_mode_enable
- gpt-slot_create
- gpt-slot_add_targeting
- gpt-slot_fill
- gpt-slot_fetch
- gpt-slot_receiving
- gpt-slot_render_delay
- gpt-slot_rendering
- gpt-slot_rendered
- gpt-google_js_loaded
- gpt-gpt_fetch
- gpt-gpt_fetched
- gpt-page_load_complete
- gpt-queue_start
- gpt-service_add_slot
- gpt-service_add_targeting
- gpt-service_collapse_containers_enable
- gpt-service_create
- gpt-service_single_request_mode_enable
- gpt-slot_create
- gpt-slot_add_targeting
- gpt-slot_fill
- gpt-slot_fetch
- gpt-slot_receiving
- gpt-slot_render_delay
- gpt-slot_rendering
- gpt-slot_rendered
回答by Spidi
Load script in the part of your page:
在页面的一部分加载脚本:
// set global variable if not already set
var googletag = googletag || {};
googletag.cmd = googletag.cmd || [];
// load asynchronously the GPT JavaScript library used by DFP,
// using SSL/HTTPS if necessary
(function() {
var gads = document.createElement('script');
gads.async = true;
gads.type = 'text/javascript';
var useSSL = 'https:' === document.location.protocol;
gads.src = (useSSL ? 'https:' : 'http:') + '//www.googletagservices.com/tag/js/gpt.js';
var node =document.getElementsByTagName('script')[0];
node.parentNode.insertBefore(gads, node);
})();
Initialise google publisher tag with the following script, preferable as well in the section of your page:
使用以下脚本初始化 google 发布商标记,最好在您的页面部分中:
// can be moved as well in the body
// if using async mode, wrap all the javascript into googletag.cmd.push!
googletag.cmd.push(function() {
// set page-level attributes for ad slots that serve AdSense
googletag.pubads().set("adsense_background_color", "FFFFFF");
googletag.pubads().setTargeting("topic","basketball");
// enables Single Request Architecture (SRA)
googletag.pubads().enableSingleRequest();
// Disable initial load, we will use refresh() to fetch ads.
// Calling this function means that display() calls just
// register the slot as ready, but do not fetch ads for it.
googletag.pubads().disableInitialLoad();
// Collapses empty div elements on a page when there is no ad content to display.
googletag.pubads().collapseEmptyDivs();
// Enables all GPT services that have been defined for ad slots on the page.
googletag.enableServices();
});
Register slots individually (can be generated with a foreach loop) and render them. The event listener can be registered as well per slot. Here the important part: make sure that you refresh them together to avoid ending up with the same ads on both slots (if the ad is assign to both slots) => googletag.pubads().refresh([slot1, slot2]]);
单独注册插槽(可以使用 foreach 循环生成)并渲染它们。每个插槽也可以注册事件侦听器。重要的部分是:确保将它们一起刷新以避免在两个广告位上出现相同的广告(如果广告分配给两个广告位)=> googletag.pubads().refresh([slot1, slot2]]) ;
// this code can be moved externally to improve performance
googletag.cmd.push(function() {
// define slot1
slot1 = googletag.defineSlot(
"/1234/travel/asia/food",
[728, 90],
"banner1"
)
.addService(googletag.pubads())
.setTargeting(
"interests",
["sports", "music", "movies"]
);
// prerender the slot but don't display it because of disableInitialLoad()
googletag.display("banner1");
// define slot2
slot2 = googletag.defineSlot(
"/1234/travel/asia/food",
[[468, 60], [728, 90], [300, 250]],
"banner2"
)
.addService(googletag.pubads())
.setTargeting("gender", "male")
.setTargeting("age", "20-30");
// prerender the slot but don't display it because of disableInitialLoad()
googletag.display("banner2");
// add event to sign the slot as redered or not
googletag.pubads().addEventListener('slotRenderEnded', function(event) {
if (event.slot === slot1 || event.slot === slot2) {
// do something related to the slot
}
});
// refresh all container ads and show them
// very important to call refresh with an array to avoid
// multiple callback to the registered event
googletag.pubads().refresh([slot1, slot2]);
});
<div id="banner1" style="width:300px; height:250px;"></div>
<div id="banner2" style="width:300px; height:250px;"></div>
After the ad has been rendered, the callback gets triggered.
广告呈现后,回调被触发。
For more information have a look on this file: https://github.com/davidecantoni/googletag
有关更多信息,请查看此文件:https: //github.com/davidecantoni/googletag
回答by Aman Verma
If you need to identify the render end of a specific slot ( useful if you are using same creative for multiple slots ) you can do the following
如果您需要确定特定广告位的渲染结束(如果您对多个广告位使用相同的创意非常有用),您可以执行以下操作
googleAd = googletag.defineSlot('/xxxxx/web_top_AAAxAAA', [xxx, xxx], 'div-id').addService(googletag.pubads());
googletag.pubads().addEventListener('slotRenderEnded', function(event) {
if( event.slot.W == googleAd.W ){
// your code here
}
});
回答by alexp
I'm pretty sure that DFP doesn't provide for a callback after the ad has rendered. I have used the following code to do this. It calls the callback function after one of the following has happened:
我很确定 DFP 不会在广告呈现后提供回调。我使用以下代码来做到这一点。它在发生以下情况之一后调用回调函数:
-The ad has loaded and the iframe has rendered
- 广告已加载且 iframe 已呈现
-No ad was loaded, and the ad unit was hidden by collapseEmptyDivs()
- 没有加载广告,广告单元被collapseEmptyDivs()隐藏
-A certain amount of time has passed (in this case, 2 seconds) with neither one happening. Like if there was some sort of network error connecting to DFP.
- 已经过去了一段时间(在本例中为 2 秒),但没有发生。就像连接到 DFP 时出现某种网络错误一样。
adId would be the id of your ad container
adId 将是您的广告容器的 ID
assumes you are using jQuery
假设您正在使用 jQuery
function callback() {
//your callback function - do something here
}
function getIframeHtml(iframe) {
if(iframe.contentWindow && iframe.contentWindow.document && iframe.contentWindow.document.body && iframe.contentWindow.document.body.innerHTML) {
return iframe.contentWindow.document.body.innerHTML;
}
return null;
}
var dfpNumChecks = 20;
var dfpCheckCount = 0;
var dfpCheckTimer = 100;
function dfpLoadCheck(adId) {
var nodes = document.getElementById(adId).childNodes;
if(nodes.length && nodes[0].nodeName.toLowerCase() == 'iframe' && getIframeHtml(nodes[0])) {
//the iframe for the ad has rendered
callback();
return;
} else if($('#' + adId).css('display') == 'none' || (dfpCheckCount >= dfpNumChecks)) {
//the ad unit has been hidden by collapseEmptyDivs()
callback();
return;
} else {
dfpCheckCount++;
setTimeout(function() { dfpLoadCheck(adId) }, dfpCheckTimer);
}
}
回答by Matt Cooper
Check out the jQuery DFPextension I'm working on... it is still a bit of a work in progress but provides the callback you are after.
查看我正在开发的jQuery DFP扩展程序......它仍在进行中,但提供了您所追求的回调。
An example of how to use it is in this file.
如何使用它的示例在此文件中。
You will see two callbacks are available... after each ad has loaded and after all ads have loaded. A class is also set on the ad unit container element, this can either be display-none (when no ad is found), display-block (when an ad is found) or display-original (for when no ad is found but the container div contained content to begin with, I use this for over riding certain parts of sites with ad content when required). These classes are of course useful to work with once inside the callback.
您将看到有两个回调可用......在每个广告加载后和所有广告加载后。在广告单元容器元素上还设置了一个类,这可以是 display-none(未找到广告时)、display-block(找到广告时)或 display-original(未找到广告但未找到广告时)容器 div 包含内容,我使用它来在需要时使用广告内容覆盖网站的某些部分)。这些类在回调中使用一次当然很有用。