How to deal with setting dynamic iframe content dynamically

邮差的信 提交于 2019-12-13 19:20:01

问题


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>

回答1:


Sorry, but if the iframe references a URL source from another domain, you can't access it.

http://javascript.info/tutorial/same-origin-security-policy

That being said, you can access its body, provided you have either a url from the same domain, or if you fill the attribute src with "javascript:void(0);". after that, try to access it this way:

$($('iframe').contents().get(0)).find('body')



回答2:


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.




回答3:


When you create the iframe ensure it has a src specified:

src='about:blank'

Or create a blank.html on the server and point to that



来源:https://stackoverflow.com/questions/12842572/how-to-deal-with-setting-dynamic-iframe-content-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!