javascript – Make iframe content responsive (Google DFP)

Question:

So, I have a somewhat complex problem. Knowing that you can't style the content of an <iframe> with CSS, I don't know how else to achieve the desired goal. I even tried it with JavaScript, but nothing worked, and in some tests I had the CrossOrigin error, due to trying to 'access' the content from a URL other than the origin.

I'm using Google DoubleClick for Business to show ads on a particular website. For those who don't know what DoubleClick is, an AdServer. It generates a javascript tag and the resulting content on the page will be an HTML with what was defined, in this case unfortunately it uses an iframe, somewhat outdated. 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 managed to do this with the service I currently use.

See in operation

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 outcome

Answer:

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"
      });
   });
});

See on 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;";
   }

}

See on JSFiddle

Scroll to Top