0

I have an html page that has an iframe with the src attribute pointing to another html page which already has some content in it.

parent.html

<body>
    <iframe src="child.html"></iframe>
</body>

child.html

<body>
    <p>test1</p>
</body>

parent.html also has a jquery function that tries to append a paragraph to the body of child.html:

$(function(){
    var $iframe = $("iframe");
    $iframe.ready(function(){
        $iframe.contents().find("body").append("<p>test2</p>");
    });

});

The problem is that the function is not working, the paragraph is not being added. The interesting part is that if I remove "child.html" from the src attribute of the iframe, the paragraph is being added into a blank html page.

Is it not possible to modify the content of an html document from an iframe (when the document already contains a number of elements)?

Also, there isn't any problem with the cross-domain policy.

Thanks in advance.

RPichioli
  • 3,245
  • 2
  • 25
  • 29
fifth
  • 5
  • 1
  • 3

1 Answers1

0

It looks like the code is executing before the iframe contents has actually loaded. Try this code:

$(document).ready(function(){
    var $iframe = $("iframe");
    $iframe.on('load', (function(){
        $iframe.contents().find("body").append("<p>test2</p>");
    });
});
Andrew D
  • 207
  • 1
  • 6
  • yes, it works. I tried this before and I didn't saw that there was an error being thrown in the console "Uncaught TypeError: a.indexOf is not a function". for who is interested, I used the solution from this post: http://stackoverflow.com/questions/37738732/jquery-3-0-url-indexof-error Anyway, thanks for the help, I really appreciate it – fifth Oct 29 '16 at 11:27
  • Have updated the code in my answer, thanks for the heads up :) – Andrew D Oct 29 '16 at 11:30