diff --git a/Readme.markdown b/Readme.markdown index f77e381..2ea9554 100644 --- a/Readme.markdown +++ b/Readme.markdown @@ -185,9 +185,16 @@ Available Options setLocation - This object sets geolocalization. String values are not valid. + This object sets geolocalization. String values are not valid. + + + setSafeFrameConfig + This object sets the page-level preferences for SafeFrame configuration. + + + setForceSafeFrame + This boolean configures whether all ads on the page should be forced to be rendered using a SafeFrame container. - enableSingleRequest This boolean sets whether the page ads are fetched with a single request or not, you will need to set this to false it you want to call $.dfp() more than once, typically you would do this if you are loading ad units into the page after the initial load. @@ -286,7 +293,7 @@ This script provides two callbacks which you can use to make working with DFP a This is called after each AdUnit has been blocked. - + Please see the [example-bootstrap.js](https://github.com/coop182/jquery.dfp.js/blob/master/example-bootstrap.js) file for an example of how to use these. diff --git a/jquery.dfp.js b/jquery.dfp.js index be68354..b335f01 100644 --- a/jquery.dfp.js +++ b/jquery.dfp.js @@ -31,13 +31,15 @@ // Save Scope dfpScript = this || {}; + // Setup global adunit counter + window.dfpUID = 0; + var // DFP account ID dfpID = '', // Init counters count = 0, - uid = 0, rendered = 0, // Default DFP selector @@ -99,6 +101,8 @@ setTargeting: {}, setCategoryExclusion: '', setLocation: '', + setSafeFrameConfig: undefined, + setForceSafeFrame: false, enableSingleRequest: true, collapseEmptyDivs: 'original', refreshExisting: true, @@ -229,6 +233,10 @@ googleAdUnit.defineSizeMapping(map.build()); } + if ($adUnit.data('safeframe')) { + googleAdUnit.setForceSafeFrame(true); + } + // Store googleAdUnit reference $adUnit.data(storeAs, googleAdUnit); @@ -275,7 +283,15 @@ }); } - if (dfpOptions.collapseEmptyDivs) { + if (typeof dfpOptions.setSafeFrameConfig === 'object') { + pubadsService.setSafeFrameConfig(dfpOptions.setSafeFrameConfig); + } + + if (dfpOptions.setForceSafeFrame) { + pubadsService.setForceSafeFrame(true); + } + + if (!googletag.__servicesEnabled__ && dfpOptions.collapseEmptyDivs) { pubadsService.collapseEmptyDivs(); } @@ -291,7 +307,7 @@ } } - if (dfpOptions.disableInitialLoad) { + if (!googletag.__servicesEnabled__ && dfpOptions.disableInitialLoad) { pubadsService.disableInitialLoad(); } @@ -303,37 +319,39 @@ pubadsService.setCentering(true); } - // Setup event listener to listen for renderEnded event and fire callbacks. - pubadsService.addEventListener('slotRenderEnded', function (event) { + if (!googletag.__servicesEnabled__) { + // Setup event listener to listen for renderEnded event and fire callbacks. + pubadsService.addEventListener('slotRenderEnded', function (event) { - rendered++; + rendered++; - var $adUnit = $('#' + event.slot.getSlotId().getDomId()); + var $adUnit = $('#' + event.slot.getSlotId().getDomId()); - var display = event.isEmpty ? 'none' : 'block'; + var display = event.isEmpty ? 'none' : 'block'; - // if the div has been collapsed but there was existing content expand the - // div and reinsert the existing content. - var $existingContent = $adUnit.data('existingContent'); - if (display === 'none' && $.trim($existingContent).length > 0 && - dfpOptions.collapseEmptyDivs === 'original') { - $adUnit.show().html($existingContent); - display = 'block display-original'; - } + // if the div has been collapsed but there was existing content expand the + // div and reinsert the existing content. + var $existingContent = $adUnit.data('existingContent'); + if (display === 'none' && $.trim($existingContent).length > 0 && + dfpOptions.collapseEmptyDivs === 'original') { + $adUnit.show().html($existingContent); + display = 'block display-original'; + } - $adUnit.removeClass('display-none').addClass('display-' + display); + $adUnit.removeClass('display-none').addClass('display-' + display); - // Excute afterEachAdLoaded callback if provided - if (typeof dfpOptions.afterEachAdLoaded === 'function') { - dfpOptions.afterEachAdLoaded.call(this, $adUnit, event); - } + // Excute afterEachAdLoaded callback if provided + if (typeof dfpOptions.afterEachAdLoaded === 'function') { + dfpOptions.afterEachAdLoaded.call(this, $adUnit, event); + } - // Excute afterAllAdsLoaded callback if provided - if (typeof dfpOptions.afterAllAdsLoaded === 'function' && rendered === count) { - dfpOptions.afterAllAdsLoaded.call(this, $adCollection); - } + // Excute afterAllAdsLoaded callback if provided + if (typeof dfpOptions.afterAllAdsLoaded === 'function' && rendered === count) { + dfpOptions.afterAllAdsLoaded.call(this, $adCollection); + } - }); + }); + } // this will work with AdblockPlus if(dfpScript.shouldCheckForAdBlockers() && !googletag._adBlocked_) { @@ -352,7 +370,10 @@ }, 0); } - googletag.enableServices(); + if (!googletag.__servicesEnabled__) { + googletag.enableServices(); + googletag.__servicesEnabled__ = true; + } }); @@ -394,14 +415,28 @@ } if (dfpOptions.refreshExisting && $adUnitData && $adUnit.hasClass('display-block')) { - googletag.cmd.push(function () { googletag.pubads().refresh([$adUnitData]); }); + googletag.cmd.push(function () { + googletag.pubads().refresh([$adUnitData]); + }); } else { - googletag.cmd.push(function () { googletag.display($adUnit.attr('id')); }); + googletag.cmd.push(function () { + googletag.display($adUnit.attr('id')); + }); } }); + if (dfpOptions.disableInitialLoad) { + var $ads = $adCollection.filter('.display-none').map(function () { + return $(this).data(storeAs); + }).get(); + + googletag.cmd.push(function () { + googletag.pubads().refresh($ads); + }); + } + }, /** @@ -435,8 +470,8 @@ */ getID = function ($adUnit, adUnitName) { - uid++; - return $adUnit.attr('id') || $adUnit.attr('id', adUnitName.replace(/[^A-z0-9]/g, '_') + '-auto-gen-id-' + uid).attr('id'); + window.dfpUID++; + return $adUnit.attr('id') || $adUnit.attr('id', adUnitName.replace(/[^A-z0-9]/g, '_') + '-auto-gen-id-' + window.dfpUID).attr('id'); }, @@ -475,8 +510,12 @@ $.each(dimensionGroups, function (k, v) { - var dimensionSet = v.split('x'); - dimensions.push([parseInt(dimensionSet[0], 10), parseInt(dimensionSet[1], 10)]); + if (v === 'fluid') { + dimensions.push(v); + } else { + var dimensionSet = v.split('x'); + dimensions.push([parseInt(dimensionSet[0], 10), parseInt(dimensionSet[1], 10)]); + } }); @@ -499,6 +538,8 @@ * @param {Array} $adCollection */ dfpLoader = function (options, $adCollection) { + window.googletag = window.googletag || {}; + window.googletag.cmd = window.googletag.cmd || []; function execBlockEvents() { if(dfpScript.shouldCheckForAdBlockers()) { @@ -519,9 +560,6 @@ var loaded = $.Deferred(); - window.googletag = window.googletag || {}; - window.googletag.cmd = window.googletag.cmd || []; - var gads = document.createElement('script'); gads.async = true; gads.type = 'text/javascript'; diff --git a/jquery.dfp.min.js b/jquery.dfp.min.js index 1cea571..00f8f9a 100644 --- a/jquery.dfp.min.js +++ b/jquery.dfp.min.js @@ -5,4 +5,4 @@ * Copyright 2016 Matt Cooper * Released under the MIT license */ -!function(a,b){"use strict";!function(b){"function"==typeof define&&define.amd?define(["jquery"],b):b("object"==typeof exports?require("jquery"):a.jQuery||a.Zepto)}(function(c){var d=this||{},e="",f=0,g=0,h=0,i=".adunit",j=!1,k=!1,l="googleAdUnit",m=function(a,b,g){var i;f=0,h=0,e=a,i=c(b),d.shouldCheckForAdBlockers=function(){return g?"function"==typeof g.afterAdBlocked:!1},u(g,i).then(function(){g=n(g),d.dfpOptions=g,c(function(){o(g,i),p(g,i)})})},n=function(d){var e={setTargeting:{},setCategoryExclusion:"",setLocation:"",enableSingleRequest:!0,collapseEmptyDivs:"original",refreshExisting:!0,disablePublisherConsole:!1,disableInitialLoad:!1,setCentering:!1,noFetch:!1,namespace:b,sizeMapping:{}};if("undefined"==typeof d.setUrlTargeting||d.setUrlTargeting){var f=q(d.url);c.extend(!0,e.setTargeting,{UrlHost:f.Host,UrlPath:f.Path,UrlQuery:f.Query})}return c.extend(!0,e,d),e.googletag&&a.googletag.cmd.push(function(){c.extend(!0,a.googletag,e.googletag)}),e},o=function(b,g){var i=a.googletag;g.each(function(){var a=c(this);f++;var d=s(a,b),g=r(a,d),h=t(a);a.data("existingContent",a.html()),a.html("").addClass("display-none"),i.cmd.push(function(){var f,j=a.data(l);if(j)f=j;else{var k;k=""===e?d:"/"+e+"/"+d,a.data("outofpage")?f=i.defineOutOfPageSlot(k,g):(f=i.defineSlot(k,h,g),a.data("companion")&&(f=f.addService(i.companionAds()))),f=f.addService(i.pubads())}var m=a.data("targeting");m&&c.each(m,function(a,b){f.setTargeting(a,b)});var n=a.data("exclusions");if(n){var o,p=n.split(",");c.each(p,function(a,b){o=c.trim(b),o.length>0&&f.setCategoryExclusion(o)})}var q=a.data("size-mapping");if(q&&b.sizeMapping[q]){var r=i.sizeMapping();c.each(b.sizeMapping[q],function(a,b){r.addSize(b.browser,b.ad_sizes)}),f.defineSizeMapping(r.build())}a.data(l,f),"function"==typeof b.beforeEachAdLoaded&&b.beforeEachAdLoaded.call(this,a)})}),i.cmd.push(function(){var a=i.pubads();b.enableSingleRequest&&a.enableSingleRequest(),c.each(b.setTargeting,function(b,c){a.setTargeting(b,c)});var e=b.setLocation;if("object"==typeof e&&("number"==typeof e.latitude&&"number"==typeof e.longitude&&"number"==typeof e.precision?a.setLocation(e.latitude,e.longitude,e.precision):"number"==typeof e.latitude&&"number"==typeof e.longitude&&a.setLocation(e.latitude,e.longitude)),b.setCategoryExclusion.length>0){var j,k=b.setCategoryExclusion.split(",");c.each(k,function(b,d){j=c.trim(d),j.length>0&&a.setCategoryExclusion(j)})}b.collapseEmptyDivs&&a.collapseEmptyDivs(),b.disablePublisherConsole&&a.disablePublisherConsole(),b.companionAds&&(i.companionAds().setRefreshUnfilledSlots(!0),b.disableInitialLoad||a.enableVideoAds()),b.disableInitialLoad&&a.disableInitialLoad(),b.noFetch&&a.noFetch(),b.setCentering&&a.setCentering(!0),a.addEventListener("slotRenderEnded",function(a){h++;var d=c("#"+a.slot.getSlotId().getDomId()),e=a.isEmpty?"none":"block",i=d.data("existingContent");"none"===e&&c.trim(i).length>0&&"original"===b.collapseEmptyDivs&&(d.show().html(i),e="block display-original"),d.removeClass("display-none").addClass("display-"+e),"function"==typeof b.afterEachAdLoaded&&b.afterEachAdLoaded.call(this,d,a),"function"==typeof b.afterAllAdsLoaded&&h===f&&b.afterAllAdsLoaded.call(this,g)}),d.shouldCheckForAdBlockers()&&!i._adBlocked_&&setTimeout(function(){var e=a.getSlots?a.getSlots():[];e.length>0&&c.get(e[0].getContentUrl()).always(function(a){200!==a.status&&c.each(e,function(){var a=c("#"+this.getSlotId().getDomId());b.afterAdBlocked.call(d,a,this)})})},0),i.enableServices()})},p=function(b,e){var f=a.googletag;if(d.shouldCheckForAdBlockers()&&!f._adBlocked_&&f.getVersion){var g="//partner.googleadservices.com/gpt/pubads_impl_"+f.getVersion()+".js";c.getScript(g).always(function(a){a&&"error"===a.statusText&&c.each(e,function(){b.afterAdBlocked.call(d,c(this))})})}e.each(function(){var a=c(this),e=a.data(l);f._adBlocked_&&d.shouldCheckForAdBlockers()&&b.afterAdBlocked.call(d,a),f.cmd.push(b.refreshExisting&&e&&a.hasClass("display-block")?function(){f.pubads().refresh([e])}:function(){f.display(a.attr("id"))})})},q=function(b){var c=(b||a.location.toString()).match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/),d=c[4]||"",e=(c[5]||"").replace(/(.)\/$/,"$1"),f=c[7]||"",g=f.replace(/\=/gi,":").split("&");return{Host:d,Path:e,Query:g}},r=function(a,b){return g++,a.attr("id")||a.attr("id",b.replace(/[^A-z0-9]/g,"_")+"-auto-gen-id-"+g).attr("id")},s=function(a,b){var c=a.data("adunit")||b.namespace||a.attr("id")||"";return"function"==typeof b.alterAdUnitName&&(c=b.alterAdUnitName.call(this,c,a)),c},t=function(a){var b=[],d=a.data("dimensions");if(d){var e=d.split(",");c.each(e,function(a,c){var d=c.split("x");b.push([parseInt(d[0],10),parseInt(d[1],10)])})}else b.push([a.width(),a.height()]);return b},u=function(b,e){function f(){d.shouldCheckForAdBlockers()&&c.each(e,function(){b.afterAdBlocked.call(d,c(this))})}if(k=k||c('script[src*="googletagservices.com/tag/js/gpt.js"]').length)return j&&f(),c.Deferred().resolve();var g=c.Deferred();a.googletag=a.googletag||{},a.googletag.cmd=a.googletag.cmd||[];var h=document.createElement("script");h.async=!0,h.type="text/javascript",h.onerror=function(){v(),g.resolve(),j=!0,f()},h.onload=function(){googletag._loadStarted_||(googletag._adBlocked_=!0,f()),g.resolve()};var i="https:"===document.location.protocol;h.src=(i?"https:":"http:")+"//www.googletagservices.com/tag/js/gpt.js";var l=document.getElementsByTagName("script")[0];return l.parentNode.insertBefore(h,l),"none"===h.style.display&&v(),g},v=function(){var b=a.googletag,e=b.cmd,f=function(a,c,d,e){return b.ads.push(d),b.ads[d]={renderEnded:function(){},addService:function(){return this}},b.ads[d]};b={cmd:{push:function(a){a.call(d)}},ads:[],pubads:function(){return this},noFetch:function(){return this},disableInitialLoad:function(){return this},disablePublisherConsole:function(){return this},enableSingleRequest:function(){return this},setTargeting:function(){return this},collapseEmptyDivs:function(){return this},enableServices:function(){return this},defineSlot:function(a,b,c){return f(a,b,c,!1)},defineOutOfPageSlot:function(a,b){return f(a,[],b,!0)},display:function(a){return b.ads[a].renderEnded.call(d),this}},c.each(e,function(a,c){b.cmd.push(c)})};c.dfp=c.fn.dfp=function(a,c){c=c||{},a===b&&(a=e),"object"==typeof a&&(c=a,a=c.dfpID||e);var d=this;return"function"==typeof this&&(d=i),m(a,d,c),this}})}(window); \ No newline at end of file +!function(a,b){"use strict";!function(b){"function"==typeof define&&define.amd?define(["jquery"],b):b("object"==typeof exports?require("jquery"):a.jQuery||a.Zepto)}(function(c){var d=this||{};a.dfpUID=0;var e="",f=0,g=0,h=".adunit",i=!1,j=!1,k="googleAdUnit",l=function(a,b,h){var i;f=0,g=0,e=a,i=c(b),d.shouldCheckForAdBlockers=function(){return h?"function"==typeof h.afterAdBlocked:!1},t(h,i).then(function(){h=m(h),d.dfpOptions=h,c(function(){n(h,i),o(h,i)})})},m=function(d){var e={setTargeting:{},setCategoryExclusion:"",setLocation:"",enableSingleRequest:!0,collapseEmptyDivs:"original",refreshExisting:!0,disablePublisherConsole:!1,disableInitialLoad:!1,setCentering:!1,noFetch:!1,namespace:b,sizeMapping:{}};if("undefined"==typeof d.setUrlTargeting||d.setUrlTargeting){var f=p(d.url);c.extend(!0,e.setTargeting,{UrlHost:f.Host,UrlPath:f.Path,UrlQuery:f.Query})}return c.extend(!0,e,d),e.googletag&&a.googletag.cmd.push(function(){c.extend(!0,a.googletag,e.googletag)}),e},n=function(b,h){var i=a.googletag;h.each(function(){var a=c(this);f++;var d=r(a,b),g=q(a,d),h=s(a);a.data("existingContent",a.html()),a.html("").addClass("display-none"),i.cmd.push(function(){var f,j=a.data(k);if(j)f=j;else{var l;l=""===e?d:"/"+e+"/"+d,a.data("outofpage")?f=i.defineOutOfPageSlot(l,g):(f=i.defineSlot(l,h,g),a.data("companion")&&(f=f.addService(i.companionAds()))),f=f.addService(i.pubads())}var m=a.data("targeting");m&&c.each(m,function(a,b){f.setTargeting(a,b)});var n=a.data("exclusions");if(n){var o,p=n.split(",");c.each(p,function(a,b){o=c.trim(b),o.length>0&&f.setCategoryExclusion(o)})}var q=a.data("size-mapping");if(q&&b.sizeMapping[q]){var r=i.sizeMapping();c.each(b.sizeMapping[q],function(a,b){r.addSize(b.browser,b.ad_sizes)}),f.defineSizeMapping(r.build())}a.data(k,f),"function"==typeof b.beforeEachAdLoaded&&b.beforeEachAdLoaded.call(this,a)})}),i.cmd.push(function(){var a=i.pubads();b.enableSingleRequest&&a.enableSingleRequest(),c.each(b.setTargeting,function(b,c){a.setTargeting(b,c)});var e=b.setLocation;if("object"==typeof e&&("number"==typeof e.latitude&&"number"==typeof e.longitude&&"number"==typeof e.precision?a.setLocation(e.latitude,e.longitude,e.precision):"number"==typeof e.latitude&&"number"==typeof e.longitude&&a.setLocation(e.latitude,e.longitude)),b.setCategoryExclusion.length>0){var j,k=b.setCategoryExclusion.split(",");c.each(k,function(b,d){j=c.trim(d),j.length>0&&a.setCategoryExclusion(j)})}b.collapseEmptyDivs&&a.collapseEmptyDivs(),b.disablePublisherConsole&&a.disablePublisherConsole(),b.companionAds&&(i.companionAds().setRefreshUnfilledSlots(!0),b.disableInitialLoad||a.enableVideoAds()),b.disableInitialLoad&&a.disableInitialLoad(),b.noFetch&&a.noFetch(),b.setCentering&&a.setCentering(!0),a.addEventListener("slotRenderEnded",function(a){g++;var d=c("#"+a.slot.getSlotId().getDomId()),e=a.isEmpty?"none":"block",i=d.data("existingContent");"none"===e&&c.trim(i).length>0&&"original"===b.collapseEmptyDivs&&(d.show().html(i),e="block display-original"),d.removeClass("display-none").addClass("display-"+e),"function"==typeof b.afterEachAdLoaded&&b.afterEachAdLoaded.call(this,d,a),"function"==typeof b.afterAllAdsLoaded&&g===f&&b.afterAllAdsLoaded.call(this,h)}),d.shouldCheckForAdBlockers()&&!i._adBlocked_&&setTimeout(function(){var e=a.getSlots?a.getSlots():[];e.length>0&&c.get(e[0].getContentUrl()).always(function(a){200!==a.status&&c.each(e,function(){var a=c("#"+this.getSlotId().getDomId());b.afterAdBlocked.call(d,a,this)})})},0),i.enableServices()})},o=function(b,e){var f=a.googletag;if(d.shouldCheckForAdBlockers()&&!f._adBlocked_&&f.getVersion){var g="//partner.googleadservices.com/gpt/pubads_impl_"+f.getVersion()+".js";c.getScript(g).always(function(a){a&&"error"===a.statusText&&c.each(e,function(){b.afterAdBlocked.call(d,c(this))})})}if(e.each(function(){var a=c(this),e=a.data(k);f._adBlocked_&&d.shouldCheckForAdBlockers()&&b.afterAdBlocked.call(d,a),f.cmd.push(b.refreshExisting&&e&&a.hasClass("display-block")?function(){f.pubads().refresh([e])}:function(){f.display(a.attr("id"))})}),b.disableInitialLoad){var h=e.filter(".display-none").map(function(){return c(this).data(k)}).get();f.pubads().refresh(h)}},p=function(b){var c=(b||a.location.toString()).match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/),d=c[4]||"",e=(c[5]||"").replace(/(.)\/$/,"$1"),f=c[7]||"",g=f.replace(/\=/gi,":").split("&");return{Host:d,Path:e,Query:g}},q=function(b,c){return a.dfpUID++,b.attr("id")||b.attr("id",c.replace(/[^A-z0-9]/g,"_")+"-auto-gen-id-"+a.dfpUID).attr("id")},r=function(a,b){var c=a.data("adunit")||b.namespace||a.attr("id")||"";return"function"==typeof b.alterAdUnitName&&(c=b.alterAdUnitName.call(this,c,a)),c},s=function(a){var b=[],d=a.data("dimensions");if(d){var e=d.split(",");c.each(e,function(a,c){var d=c.split("x");b.push([parseInt(d[0],10),parseInt(d[1],10)])})}else b.push([a.width(),a.height()]);return b},t=function(b,e){function f(){d.shouldCheckForAdBlockers()&&c.each(e,function(){b.afterAdBlocked.call(d,c(this))})}if(j=j||c('script[src*="googletagservices.com/tag/js/gpt.js"]').length)return i&&f(),c.Deferred().resolve();var g=c.Deferred();a.googletag=a.googletag||{},a.googletag.cmd=a.googletag.cmd||[];var h=document.createElement("script");h.async=!0,h.type="text/javascript",h.onerror=function(){u(),g.resolve(),i=!0,f()},h.onload=function(){googletag._loadStarted_||(googletag._adBlocked_=!0,f()),g.resolve()};var k="https:"===document.location.protocol;h.src=(k?"https:":"http:")+"//www.googletagservices.com/tag/js/gpt.js";var l=document.getElementsByTagName("script")[0];return l.parentNode.insertBefore(h,l),"none"===h.style.display&&u(),g},u=function(){var b=a.googletag,e=b.cmd,f=function(a,c,d){return b.ads.push(d),b.ads[d]={renderEnded:function(){},addService:function(){return this}},b.ads[d]};b={cmd:{push:function(a){a.call(d)}},ads:[],pubads:function(){return this},noFetch:function(){return this},disableInitialLoad:function(){return this},disablePublisherConsole:function(){return this},enableSingleRequest:function(){return this},setTargeting:function(){return this},collapseEmptyDivs:function(){return this},enableServices:function(){return this},defineSlot:function(a,b,c){return f(a,b,c,!1)},defineOutOfPageSlot:function(a,b){return f(a,[],b,!0)},display:function(a){return b.ads[a].renderEnded.call(d),this}},c.each(e,function(a,c){b.cmd.push(c)})};c.dfp=c.fn.dfp=function(a,c){c=c||{},a===b&&(a=e),"object"==typeof a&&(c=a,a=c.dfpID||e);var d=this;return"function"==typeof this&&(d=h),l(a,d,c),this}})}(window); \ No newline at end of file