Determine current / own iframe
What is the best way to determine the iframe
DOM element a page is being displayed in ?
I need to notify the parent window when the iframe's contents have really finished loading (iframe onload
looks like a scam with WebKit).
Consider the following scenario:
- Parent window loads a new iframe
- The loaded iframe invokes a function from the parent window and sends along a reference to its iframe DOM element (sort of a "sender" parameter).
- The parent's invoked function destroys the iframe.
Suggestions on alternative solutions to this inter-frame communication are also welcome.
One problem I faced was that Safari / Chrome / WebKit browsers apparently fire the iframe's onload
event too early – I tried sending form data (with file upload) to an iframe an开发者_如何学God had the onload
handler clear the <input type="file" />
element's value and destroy the iframe, causing the form submission to be aborted, so I cannot use onload
in that case (btw, is that a feature or a bug ?).
Another use case is where the iframe does something and wants interact with the parent.
Like Stefaan id say window.parent
but you should check window.frameElement too.
With window.parent you can get the parent window. You can also call methods on it. So with the following code you can notifiy the iframe parent that you have finished loading (you need to have a notifyLoaded function in the parent window.
window.parent.notifyLoaded(window);
Because we gave our own window the parent can loop all known iframes and check which one is loaded (using iframe.contentWindow to get the window of a certain iframe)
There are several ways to communicate between a frame and it's parent.
The easiest is if both have same document.domain
set, in which case they can communicate directly.
if not there are several different ways of doing cross domain communication, for instance by setting/reading the hash-component of the iframe url
Look here for more information
You can walk all iframe-elements inside the parent document and compare the contentWindow-property of the iframe-elements with the window-object inside the iframe(should be equal, but I didn't test it yet)
P.S.: tested it now, works fine http://www.jsfiddle.net/doktormolle/CMdLZ/
精彩评论