开发者

What's the topmost iframe in the same domain?

开发者 https://www.devze.com 2022-12-31 11:51 出处:网络
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

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 <-- sh开发者_开发百科ould 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.


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's answer will not find the topmost same domain window in the perverse case where a window from a different domain sits between two same-domain windows. To handle that case we need to always traverse all the way to the topmost window and separately track windows from the same domain.

The implementation below does a couple of other nice things: (a) it uses the current window by default so it can be called without any arguments in the most common case and (b) it eliminates the unnecessary tail recursion in favor of a simple while loop.

function topSameDomainWindow(win) {
  win = win || window;
  var top = win;
  while (win.parent != win) {
    try {
      // Will throw when the parent window is from a different domain
      win.parent.document;
      top = win;
    } catch (e) {}
    win = win.parent;
  }
  return top;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消