Accessing parent page with javascript inside an iframe
Is there any way to "break out" of an iframe? What I mean by this is that people will be pla开发者_开发百科cing my javascript tag inside an iframe (sometimes it ends up being nested iframes, but lets just deal with ONE for a now). I'm trying to gather certain information, like where that iframe is located on the page. It's easy enough to do it when you're not in an iframe with a mix of offsetLeft/offsetTop/innerHeight/innerWidth, but I know that you can't (or aren't supposed to be able) to see anything outside the iframe your in (assuming different domains, which it will be).
Anybody have any tips on this? Or at least any resources I could look into more? While I would eventually love to be able to access the DOM of the original page, with JS inside an iframe, I know that's not really possible. For a now I'd be happy to just figure out where the iframe is located on the page. I'm not sure if that information is part of the DOM, or browser properties (which I believe you can still access?)
Thanks!
The short answer is no.
The longer answer is that with CORS and cross frame/domain messaging you are now better off than previously. But you will get a fat "ACCESS DENIED" if you try to access the DOM in the parent frame from another domain.
If you put some javascript in the parent that can load stuff like images that set cookies on your server, then yes. but I guess that is not what you mean
Here is an example on how you can get the origin - have the users of your iframe load it like this:
<script type="text/javascript">
document.write('<script src="yourIframeLoader.php?parent='+escape(location.href)+'"><\/script>');
</script>
This doesn't work cross-domain. It's a major security feature to keep javascript from working between domains (it's called the same-origin policy).
Imagine you start on some evil site: www.evil.com
. From there, somehow, they trick you into clicking on a link that you expect to take you to a sensitive site (paypal, your bank, whatever). Instead of actually sending you to that site though, they actually iFrame it in. You go ahead and log in. BAM.
If their scripts had access to the cross-domain iFrame's DOM, they could easily snag any of the data that you're passing through the log in forms. Nasty, eh? There's just no way to deal with this safely, so it's shut off (except, arguably, JSONP)
You can always implement some javascript functions on the parent page and call them from within the iframe by calling parent.Myfunction();
As for determining the position of the iframe, I'm not sure on that one.
While an iFrame can't directly change its parent, the parent can read data from the iFrame.
This means that the parent HTML page can use JS to look at data in child iFrames.
If you control both the parent and the iFrame content, then you can set up message passing from the iFrame to the parent through an agreed element id in the iFrame.
精彩评论