views:

31

answers:

1

How can I get the topmost iframe which is in the same domain, i.e.

iframe level 1 example.org
    iframe level 2 example.org
    iframe level 2 example.org 
        iframe level 3 example.org <-- should return iframe level 1

iframe level 1 other-example.org
    iframe level 2 example.org
    iframe level 2 example.org 
        iframe level 3 example.org <-- should return iframe level 2

iframe level 1 other-example.org
    iframe level 2 example.org
    iframe level 2 example.org <-- should return iframe level 2 (this)

I need it because I have a website which should work in an iframe of another domain and stand-alone.

In this website there are scripts which depend on window.top which shouldn't be top but the topmost iframe in the same domain.

+3  A: 

If you try to access the parent and it's from a different domain, you get an error. You could use this to recursively try to access the parent until it fails, something like:

function getTopIframe(win) {
  try {
    return getTopIframe(win.parent);
  } catch(e) {
    return win;
  }
}

Edit:

The topmost window is it's own parent, so you would need a check for that to prevent an eternal loop if the top window is in the same domain:

function getTopIframe(win) {
  try {
    if (win.parent != win) {
      return getTopIframe(win.parent);
    }
  } catch(e) {
  }
  return win;
}
Guffa
+1 clever and simple!
Pekka
thank you, very clever
Jakob Stoeck