如何处理动态iframe动态设置 [英] How to deal with setting dynamic iframe content dynamically

查看:164
本文介绍了如何处理动态iframe动态设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个页面,我需要动态创建一个iframe并将其粘贴到页面上的div中。我创建这样的iframe:

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

根据某些条件,我需要:A)将iframe src设置为其他页面B)动态添加一些HTML到iframe。



我有选项A工作正常,但选项B抛出安全错误:

  if(someCondition){
//选项A,工作正常
frame.attr('src',someURL);
} else {
//选项B,吹灭访问被拒绝。
$(frame [0] .contentWindow.document).find('body')。html(someHTML);
}

我需要设置 document.domain 在动态iframe之前尝试设置HTML?我该怎么办呢?是否有更简单的方式将动态内容追加到动态iframe?



提前感谢。



编辑这里是动态iframe的呈现HTML,如下所示:

 < div id =someDiv > 
< iframe id =myIframeclass =someClass>< / iframe>
< / div>


解决方案

我能够使用类似于答案的修复此问题,以摆脱问题:

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

每个定义都是一个黑客,但我认为这是解决问题的最佳方式。 / p>

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>

解决方案

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.

这篇关于如何处理动态iframe动态设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆