1

I created an iframe with content dynamically loaded with jquery like this and I want the iframe document to access its content as soon as it has been loaded:

jQuery('<iframe>', {
    id: 'widgetFrm',
    width: '100%'
})
.appendTo('#widgetDiv')
.on('load', function () {
    jQuery(this).contents().find('body').append(data.html);
})

The frame document knows about jquery because I use

if (typeof(jQuery) == "undefined") {
    var iframeBody = document.getElementsByTagName("body")[0];
    var jQuery = function (selector) { return parent.jQuery(selector, iframeBody);
}

there. Within the iframe, I'd like to access its div elements after everything got loaded, I'm using jQuery(document).ready for that (within the dynamically loaded content).

Problem: Accessing its own elements in the frame document somehow does not work with jquery 1.x in document ready block! document.getElementById('#someDiv') returns null and jQuery('#someDiv').prop('scrollHeight') returns undefined, although the frame content has that element (accessing it when clicking a button works!). With newer jQuery versions (for instance 3.3.1) it works, but I can't change that version currently. Is there another way to do that? Thank you!

Harshit
  • 886
  • 7
  • 18
browie901
  • 11
  • 3
  • Do you have editing access to the page within the iframe? In other words: Can you logon to the page within iframe and then edit that page? – zer00ne Feb 12 '19 at 17:58
  • The iframe created in the snippet would not have an src, so it's page would be about:blank – Taplar Feb 12 '19 at 18:01
  • I'm now just guessing, but It might be that document.ready isn't properly triggered on the frame node.You could try to replace that with pure JS `document.addEventListener('DOMContentLoaded', fn, false);` – Goran.it Feb 12 '19 at 18:04
  • Yes I have access to the content of the data as it's my own loaded from a server. The iframe does not have a src, but data.html is valid and correctly set as the iframe's content – browie901 Feb 12 '19 at 18:05
  • "but data.html is valid and correctly set as the iframe's content" how, and where? that's pertenent information – Taplar Feb 12 '19 at 18:05
  • Also side note; `document.getElementsByTagName("body")[0];` <-- don't do that. Just use `document.body`. – Taplar Feb 12 '19 at 18:07
  • @Taplar data is content that I load via jsonp and jQuery.getJSON. It contains some divs in body, after that the jquery definition and then `jQuery(document).ready( function () { alert(document.getElementById('#someDiv')) });` and this always returns null although someDiv exists in frame content. – browie901 Feb 12 '19 at 18:19
  • That doesn't explain the missing part of your question where the src of the iframe is set. – Taplar Feb 12 '19 at 18:20
  • The src of the iframe is not set it all, found the way to do that in https://stackoverflow.com/questions/4119979/create-an-iframe-element-and-append-html-content-to-it-with-jquery – browie901 Feb 12 '19 at 18:34

0 Answers0