iframe contentWindow throws Access Denied error after shortening document.domain
我通过以下方式动态创建一个IFRAME:
1 2 3 4 | var wrapUpIframe = document.createElement("iframe"); wrapUpIframe.id = 'WrapUpDialog3'; wrapUpIframe.src = 'WrapUpDialog.html'; document.body.appendChild(wrapUpIframe); |
动态创建后,我的
但是当我尝试访问
1 | document.getElementById("WrapUpDialog3").contentWindow.SomeFunction(); |
注意:当我在HTML中静态定义IFRAME时,它可以正常工作。
我还尝试通过以下方式更改IFRAME
1 | WrapUpDialog3.document.domain = dc.com; |
我同时检查了
我该怎么办?
我正在使用IE9。
首先查看此帖子的正确答案。在我看来,这可能是您的问题。
如果不是那样的话,那么也许我从另一篇文章中看到的这种快速技巧可能会有所帮助。
1 2 3 4 5 | var frame = $('<iframe>') .attr('id', 'myIframe') .addClass('someClass') .attr('src', 'javascript:(function () {' +'document.open();document.domain=\'myDomain.net\';document.close();' + '})();'); .appendTo($('#someDiv')); |
不确定这是否相关,但我也在Web链接上找到了它。
好的,请回复您的评论。 javascript函数未分配源,而是设置了文档域,这显然在I.E.
中无法正确完成。
查看此链接以获取另一个示例和说明。
所以我尝试的可能是这样的...
1 2 3 4 5 6 | var wrapUpIframe = document.createElement("iframe"); wrapUpIframe.id = 'WrapUpDialog3'; wrapUpIframe.src = setSrc(); document.body.appendChild(wrapUpIframe); function setSrc(){document.open();document.domain=\'dc.com\';document.close();return 'WrapUpDialog.html';} |
在运行设置文档域的函数之后,您可能必须尝试如何返回iframe的实际网址。但是从我看来,这可能对您有用。
我遇到了类似的问题,但问题并不完全相同,这就是为什么我无法为您提供确切的解决方法。设置文档域的功能使我摆脱了拒绝访问错误。
您也可以将其添加到主文档中,以确保域匹配。
1 2 | <script type="text/javascript"> document.domain = 'dc.com'; |
我还想添加一个链接,以获取有关明确设置以前使用的document.domain的一些说明。过去这对我很有帮助。特别是这个报价...
Explicitly setting the value indicates intent to"cooperate" with a
script on another subdomain (under the same parent domain).
Dor,您可能遇到计时问题。我找到了一些我刚刚测试过的代码,这些代码对我来说很有效。它确保在尝试访问contentWindow之前已加载iframe。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | var iframe = document.createElement("iframe"); iframe.src ="WrapUpDialog.html"; if (iframe.attachEvent){ iframe.attachEvent("onload", function(){ alert("Local iframe is now loaded."); }); } else { iframe.onload = function(){ alert("Local iframe is now loaded."); }; } document.body.appendChild(iframe); var iframeWindow = iframe.contentWindow || iframe.contentDocument.parentWindow; |
您如何提供文件?您在地址栏中看到
如果我使用
由于您尚未接受任何答案,因此您可能仍然遇到问题。
尝试在两个HTML页面中显式设置
1 | document.domain = 'dc.com'; |
这意味着您的代码将如下所示:
1 2 3 4 5 | document.domain = 'dc.com'; var wrapUpIframe = document.createElement("iframe"); wrapUpIframe.id = 'WrapUpDialog3'; wrapUpIframe.src = 'WrapUpDialog.html'; document.body.appendChild(wrapUpIframe); |
然后,在
1 | document.domain = dc.com; |
因此您的这一行将不起作用:
1 | WrapUpDialog3.document.domain = 'dc.com'; |
因为
此页面上有更多信息:document.domain = document.domain做什么?。
最终提示:请使用其他浏览器(例如IE9,Firefox,Google Chrome)尝试代码。这可以帮助您确定您是否正在处理一个特定浏览器的怪癖。