Search code examples
javascriptjquerydomiframesame-origin-policy

How to deal with setting dynamic iframe content dynamically


I have a page where I need to dynamically create an iframe and stick it into a div on the page. I create the iframe like this:

var frame = $('<iframe>')
    .attr('id', 'myIframe')
    .addClass('someClass')
    .appendTo($('#someDiv'));

Depending on some condition, I need to either: A) set the iframe src to some other page OR B) dynamically add some HTML to the iframe.

I have option A working fine, but option B is throwing security errors:

if (someCondition) {
    // option A, works fine
    frame.attr('src', someURL);
} else {
    // option B, blows up with "Access is denied."
    $(frame[0].contentWindow.document).find('body').html(someHTML);
}

Do I need to set the document.domain on the dynamic iframe before attempting to set the HTML? How would I even do that? Is there an easier way to append dynamic content to a dynamic iframe?

Thanks in advance.

Edit here is the rendered HTML of the dynamic iframe, as requested:

<div id="someDiv">
    <iframe id="myIframe" class="someClass"></iframe>
</div>

Solution

  • I was able to use a fix similar to the answer to this question in order to get around the issue:

    var frame = $('<iframe>')
        .attr('id', 'myIframe')
        .addClass('someClass')
        .attr('src', 'javascript:(function () {' + 
            'document.open();document.domain=\'myDomain.net\';document.close();' + 
         '})();');
        .appendTo($('#someDiv'));
    

    It's a hack by every definition, but I think it is the best way to solve the problem.