1

I have a div on a page that is used by Google to write out a child div and child iframe ad inside of it.

<div id="ads-pos-111" class="module ad ad-111" data-pos="922"></div>

When the iframe ad is written, the DOM looks like this:

<div id="ads-pos-111" class="module ad ad-111" data-pos="922">
    <div id="google_ads_iframe_/123456/consumer/hco_3__container__" style="border: 0pt none;">
         <iframe id="google_ads_iframe_/123456/consumer/hco_3" title="3rd party ad content" name="google_ads_iframe_/123456/consumer/hco_3" width="1" height="8" scrolling="no" marginwidth="0" marginheight="0" frameborder="0" srcdoc="" style="border: 0px; vertical-align: bottom; width: 100%; height: 578px; margin: 0px;"></iframe>
    </div>
</div>

I want to write Javascript code inside the iframe that can traverse its ancestors to get the value of the data-pos attribute two ancestors above. I would like to use something like jQuery.closest('.data-pos').

I cannot use the iframe name as an anchor point as the name is generated dynamically by Google. Nor can I use the parent div ID, as there are potentially multiple ads on the page. So,I can't use code like window.parent.$('#google_ads_iframe_/123456/consumer/hco_3') as I won't know the ID. Each iframe needs to "self-detect" what "data-pos" it is located in.

Has anybody encountered this situation? (iframes are served on same domain as parent page)

Jino Shaji
  • 1,097
  • 14
  • 27
Stephen
  • 2,410
  • 3
  • 33
  • 57
  • 1
    If there are no cross-domain issues, see https://stackoverflow.com/questions/11806947/is-it-possible-that-iframe-resize-itself-without-help-from-main-window/11807287#11807287 . – Teemu Sep 14 '17 at 17:44
  • Is there only going to be one iframe on the page? If so, just use $('iframe').parent().parent().attr('data-pos') to get what you're looking for once it renders. Here's a jsbin: http://jsbin.com/hafutekacu/edit?html,js,console – yoursweater Sep 14 '17 at 18:15
  • @yoursweater: There are many iframes on the page as Google is serving a bunch of ads. So, your syntax cannot help me. Teemu's answer seems to be what I am looking for. – Stephen Sep 14 '17 at 18:31
  • 1
    @Teemu: Thanks for the link. I did not know window.frameElement existed. Just tested it and I was able to get the value. – Stephen Sep 14 '17 at 19:03

0 Answers0