首先,两个框架必须在同一个域上运行,因为如果它们是不同的域,浏览器会阻止一个框架中的代码访问另一个框架中的任何内容。如果这两个框架不在同一个域中,则 iframe 将必须监控自己并在使用完 window.postMessage() 之类的内容后通知另一个框架。
如果它们在同一个域中,这会稍微复杂一些。您必须获取 iframe 元素(在您的主文档中)。你必须等待它准备好(因为它必须加载它自己的内容)。然后,您必须在 iframe 中获取文档。然后您可以在 iframe 中找到所需的图像。然后你可以观察它的内容。当然,如果 iframe 与您的主页位于同一个域(由于安全限制),您只能执行上述任何操作。
首先,在 iframe 中添加一个 id:
<iframe id="myFrame" seamless width="100%" frameborder="0" height="80%" src="http://fritz.box/usb/usb_diskcut.lua?usbdev=all"></iframe>
然后,你可以使用这个:
// put this code in your document AFTER the iFrame tag
// or only run it after the DOM is loaded in your main document
function checkImageSrc(obj) {
if (obj.src.indexOf("/finished_ok_green.gif") !== -1) {
// found the green gif
// put whatever code you want here
} else {
// check repeatedly until we find the green image
setTimeout(function() {
checkImageSrc(obj);
}, 2000);
}
}
// get the iframe in my documnet
var iframe = document.getElementById("myFrame");
// get the window associated with that iframe
var iWindow = iframe.contentWindow;
// wait for the window to load before accessing the content
iWindow.addEventListener("load", function() {
// get the document from the window
var doc = iframe.contentDocument || iframe.contentWindow.document;
// find the target in the iframe content
var target = doc.getElementById("uiView_TestPic");
checkImageSrc(target);
});
仅供参考,这里有更多关于等待 iframe 准备好的详细信息:How can I access the DOM elements within an iFrame
如果您控制 iframe 中的代码,那么实现这一点的更简洁的方法是在 iframe 中的代码完成其操作时使用window.postMessage() 将消息发布到父窗口。然后父窗口就可以只监听那条消息,它会知道操作何时完成。
可能看起来像这样。将此代码放在 iframe 中:
// put this code in your document AFTER the relevant image tag
// or only run it after the DOM is loaded in your iframe
// if you can hook into the actual event that knows the unmount
// is done, that would be even better than polling for the gif to change
function checkImageSrc(obj) {
if (obj.src.indexOf("/finished_ok_green.gif") !== -1) {
// found the green gif
// notify the parent
window.parent.postMessage("unmount complete", "*");
} else {
// check repeatedly until we find the green image
setTimeout(function() {
checkImageSrc(obj);
}, 2000);
}
}
// find the target in the iframe content
var target = document.getElementById("uiView_TestPic");
checkImageSrc(target);
然后,在您的主窗口中,您会像这样收听发布的消息:
window.addEventListener("message", function(e) {
// make sure this is coming from where we expect (fill in the proper origin here)
if (e.origin !== "http://example.org:8080") return;
if (e.data === "unmount complete") {
// unmount is complete - put your code here
}
});