Well, I have an IFrame, which calls a same domain page. My problem is that I want to access some information from this parent Iframe from this called page (from JavaScript).
Maybe just use
window.parent
into your iframe to get the calling frame / windows. If you had multiple calling frame, you can use
window.top
Simply call window.frameElement from your framed page.
If the page is not in a frame then frameElement
will be null
.
The other way (getting the window element inside a frame is less trivial) but for sake of completeness:
/**
* @param f, iframe or frame element
* @return Window object inside the given frame
* @effect will append f to document.body if f not yet part of the DOM
* @see Window.frameElement
* @usage myFrame.document = getFramedWindow(myFrame).document;
*/
function getFramedWindow(f)
{
if(f.parentNode == null)
f = document.body.appendChild(f);
var w = (f.contentWindow || f.contentDocument);
if(w && w.nodeType && w.nodeType==9)
w = (w.defaultView || w.parentWindow);
return w;
}
Also you can set name and ID to equal values
<iframe id="frame1" name="frame1" src="any.html"></iframe>
so you will be able to use next code inside child page
parent.document.getElementById(window.name);
Once id of iframe is set, you can access iframe from inner document as shown below.
var iframe = parent.document.getElementById(frameElement.id);
Works well in IE, Chrome and FF.
Try this, in your parent frame set up you IFRAMEs like this:
<iframe id="frame1" src="inner.html#frame1"></iframe>
<iframe id="frame2" src="inner.html#frame2"></iframe>
<iframe id="frame3" src="inner.html#frame3"></iframe>
Note that the id of each frame is passed as an anchor in the src.
then in your inner html you can access the id of the frame it is loaded in via location.hash:
<button onclick="alert('I am frame: ' + location.hash.substr(1))">Who Am I?</button>
then you can access parent.document.getElementById() to access the iframe tag from inside the iframe
I would recommend using the postMessage API.
In your iframe, call:
window.parent.postMessage({message: 'Hello world'}, 'http://localhost/');
In the page you're including the iframe you can listen for events like this:
window.addEventListener('message', function(event) {
if(event.origin === 'http://localhost/')
{
alert('Received message: ' + event.data.message);
}
else
{
alert('Origin not allowed!');
}
}, false);
By the way, it is also possible to do calls to other windows, and not only iframes.
Read more about the postMessage API on John Resigs blog here