Access parent's DOM from script in an iframe i

2019-08-01 19:22发布

I have a framed window (currently iframe but may possibly be frame) - I do not have control over this.

I would like to detect if my content is inside an iframe (or frame).

I wanted to compare the location of the current document with the one the top object holds but it appears it is the same object (top === window).
After extensive googling I got to this IEMobile blog entry and in one of the comments there is this answer:

iemoblog said:

No, you can't access any part of the parent's DOM from script in an iframe in IE Mobile.
December 20, 2007 12:12 PM

I can't seem to find any documentation about this - can anyone help confirm this or even better - suggest a way to detect if the page is "framed"?

2条回答
狗以群分
2楼-- · 2019-08-01 19:37

The main problem is that if the frame is from a different domain then the container then your JavaScript is sandboxed and can't access the other frame/container.

What you can do is try to compare window to window.top and the possible outcomes are: 1. The are the same -> you are the top window on the page 2. They are not the same -> you are not the top window on the page, there is some container page, in the same domain as you, that holds your window as a frame or iframe. 3. A security exception is thrown -> you are not the top window on the page, but the top window is from another domain and you can't access it.

maybe something like this:

try {
  if (window == window.top)
    return "I'm parent";
  else
    return "I'm a child of " + window.top.location;
} catch (e) {
  return "I'm a child of something from another domain";
}
查看更多
混吃等死
3楼-- · 2019-08-01 19:43

As I did not get anywhere after finding the comment left in the IE Mobile blog (by Charles Morris - program manager on the IE Mobile team, on his own post) I am forced to add this answer and state it is:

As designed (or a bug at least)

prc said:

regarding iframe support: I can create an iframe, but am unable to "look outside" the frame. "top" and "parent" both seem to refer only to the iframe itself and not the topmost ancestor or immediate ancestor as the documentation suggests that it should. Is there a way to refer to javascript variables in the enclosing document from within an iframe?

December 19, 2007 9:29 PM

iemoblog said:

No, you can't access any part of the parent's DOM from script in an iframe in IE Mobile.

December 20, 2007 12:12 PM

查看更多
登录 后发表回答