I have a script which is purely JS which takes code and inserts it into an iframe:
var html = "<p>Some <strong>HTML</strong> to insert</p>"
var iframe = document.getElementById('contentsframe');
iframe = (iframe.contentWindow) ? iframe.contentWindow : (iframe.contentDocument.document) ? iframe.contentDocument.document : iframe.contentDocument;
iframe.document.open();
iframe.document.write(html);
iframe.document.close();
I was wanting to create a jQuery plugin as I am using this bit of code a lot, I have tried a few ways to get the iframe with jQuery:
var iframe = $('#contentsframe');
var iframe = $('#contentsframe').contents();
Both of these seem to return the wrong type of object that is needed to then call document.open, write or close. does anyon know the solution to this?
Cheers
Eef
I’ve been using the same code as you mention in your post, and have no problem. Try something like this:
This should append your code at the start of the iframe’s body tag.
edit: in this case the var iframe would be set to the body element of the iframe, which can be confusing. The $(‘#contentsframe’).contents() would actually reference the entire iframe object.