简体   繁体   中英

Javascript window.parent variable is never null

As known, window.parent helps people get the parent window of the current one when several iframe are used. However,there should be an outermost window whose parent is null I think .

I tried parent.parent.parent.parent... I thought I could get the root window when I found one of which parent is null. The amazing thing is that, no matter how many parent I used, the parent variable is never null.

I have a condition as below.

Website1 with domain: csm.mysite.com

Website1-1 with domain: csmnew.mysite.com

Website1-1 is in an iframe of Website1(they are not in the same domain)

The same time, in Website1-1, there are many iframe(they are in the same domain)

I need to set/get a global variable for Website1-1 , so I was using top. That really helps.

However, when Website1-1 is in Website1, an error is always thrown because top variable(in Website1-1) are referenced to Website1 and that is not valid for cross-domain policy . But what I really want is to set/get "top" variable of Website1-1.

Then I was thinking if I could use parent.parent.parent.... to get outermost window of Website1-1 instead of using top which lets me get the wrong window.

Back to the topic, why parent.parent.parent... is always null?

By the way, does anyone have idea how to get the outermost window of "Website1-1"?

Thanks alot

window.parent, in case the window does not have a parent, contains a reference to self, this is why it will never be null.

Source: https://msdn.microsoft.com/en-us/library/ms952669.aspx

To find, the outer-most window you can use window.frameElement. This works the way you expected window.parent to work:

More details here: https://developer.mozilla.org/en-US/docs/Web/API/Window/frameElement

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM