Javascript 跨域 iframe 内容加载检测
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2754282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cross domain iframe content load detection
提问by rik_davis
I have a rather interesting problem. I have a parent page that will create a modal jquery dialog with an iframe contained within the dialog. The iframe will be populated with content from a 3rd party domain. My issue is that I need to create some dialog level javascript that can detect if the content of the iframe loaded successfully and if it hasn't within a 5 second time frame, then to close the dialog and return the user to the parent page.
我有一个相当有趣的问题。我有一个父页面,它将创建一个模态 jquery 对话框,对话框中包含一个 iframe。iframe 将填充来自 3rd 方域的内容。我的问题是我需要创建一些对话框级别的 javascript,它可以检测 iframe 的内容是否成功加载以及是否在 5 秒的时间范围内没有加载,然后关闭对话框并将用户返回到父页面。
I have researched numerous solutions and only two are of any true value.
我研究了许多解决方案,只有两个具有真正的价值。
- Get the remote site to include a javascript line of document.domain = 'our-domain.com'.
- Use a URL Fragment hack, but again I would need the request that the remote site able to modify the URL by appending '#some_value' to the end of the URL and my dialog window would have to poll the URL until it either sees it or times out.
- 获取远程站点以包含 JavaScript 行 document.domain = 'our-domain.com'。
- 使用 URL Fragment hack,但我再次需要远程站点能够通过将“#some_value”附加到 URL 末尾来修改 URL 的请求,并且我的对话窗口必须轮询 URL,直到它看到它或超时。
Are these honestly the only options I have to work with? Is there not a simpler way to just detect this?
老实说,这些是我必须使用的唯一选择吗?有没有更简单的方法来检测这个?
I have been researching if there's a way to poll for http response errors, but this still remains confined to the same restrictions.
我一直在研究是否有办询 http 响应错误,但这仍然局限于相同的限制。
Any help would be immensely appreciated.
任何帮助将不胜感激。
Thanks
谢谢
采纳答案by Sean Kinsey
The easiest way (if you can get code added to the external sites) is to have them add an invisible iframe pointing to a special html file on your domain. This could then use parent.parent.foo()to notify the original window about the load event.
最简单的方法(如果您可以将代码添加到外部站点)是让他们添加一个不可见的 iframe,指向您域中的特殊 html 文件。然后,这可以parent.parent.foo()用来通知原始窗口有关加载事件的信息。
Listening for the "load" event will only tell you if the window loaded, not what was loaded or if the document is ready for interaction.
侦听“加载”事件只会告诉您窗口是否已加载,而不是已加载的内容或文档是否已准备好进行交互。
回答by juandopazo
Nicholas Zakas has an article about detecting if an iframe loaded: http://www.nczonline.net/blog/2009/09/15/iframes-onload-and-documentdomain/. Basically you have this code snippet:
Nicholas Zakas 有一篇关于检测 iframe 是否加载的文章:http: //www.nczonline.net/blog/2009/09/15/iframes-onload-and-documentdomain/。基本上你有这个代码片段:
var iframe = document.createElement("iframe");
iframe.src = "simpleinner.htm";
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);
I haven't tested it, but I'm pretty sure jQuery should be able to handle it by doing something like $("#iframe").load(function () { alert("Local iframe is now loaded."); });
我还没有测试过,但我很确定 jQuery 应该能够通过做类似的事情来处理它 $("#iframe").load(function () { alert("Local iframe is now loaded."); });
回答by Dror
You could try using postMessagefor communication between frames.
This will require the remote site to include some specific JavaScript to post a message to the parent document when it has finished loading.
您可以尝试使用postMessage进行帧之间的通信。
这将要求远程站点包含一些特定的 JavaScript,以便在加载完成后向父文档发布消息。
回答by Max Carlson
It's possible to do this with an onload handler on the iframe itself. Unfortunately (surprise!) IE makes it difficult. The only way I could get this to work was to compose HTML for the iframe, then append it to the document with innerHTML. Then I have to poll to see when the iframe appears in the DOM, which varies depending on if the page is loading. Here's a link to the source: http://svn.openlaszlo.org/openlaszlo/trunk/lps/includes/source/iframemanager.js
可以使用 iframe 本身的 onload 处理程序来做到这一点。不幸的是(惊喜!)IE 让它变得困难。我能让它工作的唯一方法是为 iframe 编写 HTML,然后将其附加到文档中innerHTML。然后我必须轮询以查看 iframe 何时出现在 DOM 中,这取决于页面是否正在加载。这是源的链接:http: //svn.openlaszlo.org/openlaszlo/trunk/lps/includes/source/iframemanager.js
See create(), __finishCreate()and gotload(). Feel free to take a copy of this and use it yourself!
见create(),__finishCreate()和gotload()。随意复制一份并自己使用!
Regards, Max Carlson OpenLaszlo.org
此致, Max Carlson OpenLaszlo.org
回答by Arun Joshla
This is how I detected the loading of a Cross-Domain Iframe,
这就是我检测跨域 Iframe 加载的方式,
- Set a unique id for the iframe ( U may use any sort of identifier, it doesn't matter )
- 为 iframe 设置一个唯一的 id(你可以使用任何类型的标识符,没关系)
<iframe id="crossDomainIframe" src=""> </iframe>
- Set window event listener:
- 设置窗口事件监听器:
document.getElementById("MICSMsgBoardIframe").addEventListener('load', function actionToPerform(){ //Do your onLoad actions here }
document.getElementById("MICSMsgBoardIframe").addEventListener('load', function actionToPerform(){ //Do your onLoad actions here }
回答by Mic
In any case you will need some sort of cooperation from the other domain's server, as you are trying to abuse the Same Origin Policy (SOP)
在任何情况下,您都需要其他域服务器的某种合作,因为您正在尝试滥用同源策略 (SOP)
The first solution document.domain=...won't work if domains are different. It works only for subdomains and ports, as described in the link above.
document.domain=...如果域不同,第一个解决方案将不起作用。它仅适用于子域和端口,如上面的链接中所述。
The only option that allows cross domain communication without polling is JSONPor script injection with a JS function callback. This method is available in all Google APIs and works well.
允许跨域通信而无需轮询的唯一选项是JSONP或带有 JS 函数回调的脚本注入。此方法在所有 Google API 中都可用并且运行良好。
We've explained on our bloga way to sandbox those calls in an iframe to secure them. While postMessageis better now, the window.name hackhas the advantage of working on old browsers.
我们在博客中解释了一种在 iframe 中对这些调用进行沙箱处理以保护它们的方法。虽然postMessage现在更好,但window.name hack具有在旧浏览器上工作的优势。
Ironically, SOP does not prevent you to POST anything to another domain. But you won't be able to read the response.
具有讽刺意味的是,SOP 不会阻止您向另一个域发布任何内容。但是您将无法阅读回复。

