14

Following is Google Chrome version for getting parent window's URL from iFrame.

window.location.ancestorOrigins;

I'm looking for equivalent of above statement for FireFox and IE. Is it possible to achieve it.

Tried with document.referrer also giving the iFrame Url only.

Ravi MCA
  • 2,491
  • 4
  • 20
  • 30
  • possible duplicate of [this](http://stackoverflow.com/questions/22523158/how-to-get-the-parent-window-url-from-iframe) – Siddharth Jan 12 '16 at 11:49
  • 4
    Not a duplicate, @Siddharth, that link only concerns parent frame, this question is about a property that shows all parent frames. – Seanonymous Apr 21 '17 at 23:56
  • 2
    For what it's worth, Mozilla have deliberately chosen not to implement the `ancestorOrigins` API in Firefox for privacy reasons. There is an [ongoing discussion](https://github.com/whatwg/html/issues/1918) on the whatwg group regarding changing the API to make use the referrer policy. – Dan Atkinson Feb 18 '20 at 14:48

5 Answers5

5

Unfortunately, FireFox and IE do not have an equivalent to ancestorOrigins.

The best you can do with regards to getting the parent URL is document.referrer and unfortunately if you are dealing with iframes, this means you may not be able to get to the outside page and get the true URL of the webpage.

Oli C
  • 1,120
  • 13
  • 36
1

I do something like this:

function getAncestorOrigins() {
  if (location.ancestorOrigins !== undefined) {
    return [...location.ancestorOrigins];
  }
  const urls = [];
  let parentWin = window;
  while (parentWin !== window.top) {
    if (parentWin.document.referrer) {
      try {
        const url = new URL(parentWin.document.referrer);
        urls.push(url.origin);
      } catch (e) {
        // console.error
      }
    }
    // @ts-ignore
    parentWin = parentWin.parent;
  }
  return urls;
}
neuronet
  • 1,139
  • 8
  • 19
0

I found this alternative solution. This works for me...

var url = window.location != window.parent.location ? 
           document.referrer :
           document.location.href;
Hp Sharma
  • 309
  • 3
  • 7
0

This is a known bug in Firefox

neuronet
  • 1,139
  • 8
  • 19
0

One way can be by checking if window.parent[0].top.document exists.

If you don't get an error when querying this object assume it's in the same domain, otherwise assume it's in different domains.

var origins = location.ancestorOrigins;
if ( ! origins ) {
  origins = { "length": 1 };
  try {
    if ( window.parent[0].top.document )
      // Chrome & Firefox (same domain)
      origins[0] = location.origin;

  } catch(err) {
    // Firefox (different domains CORS policy)      
    origins[0] = "*"; // force any domain
  };
};
console.log( origins, location.origin )
if ( origins[ origins.length -1 ] == location.origin ) {
  // same domain
  alert("Hello word!");

} else {
  // different domains
  var message = 'alert("Hello word!");';
   window.parent.postMessage( message, origins[ origins.length -1 ] );
};
fwBasic
  • 154
  • 9