Make responsive iframe content (Google DFP)

3

So, I have a somewhat complex problem. Knowing that it is not possible to CSS style the content of a <iframe> , I do not know any other way to achieve the desired goal. I even tried with JavaScript, but nothing worked, some tests I had the CrossOrigin error, due to trying to 'access' the content of a URL other than the source.

I'm using Google DoubleClick for Business to display ads on a particular site. For those who do not know what DoubleClick is, an AdServer. It generates a javascript tag and the result content on the page will be an HTML with what was set, in this case unfortunately it uses iframe, somewhat lagged. The problem is that the ads are of fixed sizes (I can define). The service does not have a native responsiveness, ie 100% width for example. Avoiding having to register creatives of several different sizes, I want to make them responsive, I was able to do this with the service I currently use.

  

See it working

Tag generated by DFP <head>

<script async='async' src='https://www.googletagservices.com/tag/js/gpt.js'></script>
  <script>
    var googletag = googletag || {};
    googletag.cmd = googletag.cmd || [];
  </script>

  <script>
    googletag.cmd.push(function () {
      googletag.defineSlot('/21690932511/oregionalsul.com/1200x160_featured', [[1200, 160], [970, 90]], 'div-gpt-ad-1521048007443-0').addService(googletag.pubads());
      googletag.pubads().enableSingleRequest();
      googletag.enableServices();
    });
  </script>

Tag <body>

  <!-- /21690932511/oregionalsul.com/1200x160_featured -->
  <div id='div-gpt-ad-1521048007443-0'>
    <script>
      googletag.cmd.push(function () { googletag.display('div-gpt-ad-1521048007443-0'); });
    </script>
  </div>
  

Expected result

    
asked by anonymous 16.03.2018 / 18:22

1 answer

2

First add to your CSS:

iframe{
   width: 100% !important;
}

Solution in jQuery using contents() :

$(window).on("load", function(){
   $("iframe").on("load", function(){
      var ads = $(this).contents().find("#aw0 img");
      ads.attr({
         "width": "100%",
         "height": "auto"
      });
   });
});

View in JSFiddle

Solution using pure JavaScript:

window.onload = function(){

   var iframe = document.body.querySelector("iframe");

   iframe.onload = function(){
      var iframeDocument = iframe.contentDocument || iframe.contentWindow.document,
      ads = iframeDocument.body.querySelector("#aw0 img");

      ads.style.cssText = "width: 100%; height: auto;";
   }

}

View in JSFiddle

    
21.03.2018 / 02:02