There is a hidden way to get a domain in Chrome and Opera (in several nested cross-domain iframes), although this is not possible in other browsers.
You need to use the window.location.ancestorOrigins property, which seems to be a small commercial secret in the advertising world. They may not like it when I post it, although I find it important to share information that can help others, and ideally share well-documented and supported code examples.
Therefore, I created the code snippet below to share, and if you think you can improve the code or comments, please feel free to edit the gist on Github so that we can do it even better:
Gist: https://gist.github.com/ocundale/281f98a36a05c183ff3f.js
Code (ES2015):
// return topmost browser window of current window & boolean to say if cross-domain exception occurred const getClosestTop = () => { let oFrame = window, bException = false; try { while (oFrame.parent.document !== oFrame.document) { if (oFrame.parent.document) { oFrame = oFrame.parent; } else { //chrome/ff set exception here bException = true; break; } } } catch(e){ // Safari needs try/catch so sets exception here bException = true; } return { 'topFrame': oFrame, 'err': bException }; }; // get best page URL using info from getClosestTop const getBestPageUrl = ({err:crossDomainError, topFrame}) => { let sBestPageUrl = ''; if (!crossDomainError) { // easy case- we can get top frame location sBestPageUrl = topFrame.location.href; } else { try { try { // If friendly iframe sBestPageUrl = window.top.location.href; } catch (e) { //If chrome use ancestor origin array let aOrigins = window.location.ancestorOrigins; //Get last origin which is top-domain (chrome only): sBestPageUrl = aOrigins[aOrigins.length - 1]; } } catch (e) { sBestPageUrl = topFrame.document.referrer; } } return sBestPageUrl; }; // To get page URL, simply run following within an iframe on the page: const TOPFRAMEOBJ = getClosestTop(); const PAGE_URL = getBestPageUrl(TOPFRAMEOBJ);
If anyone wants to use the code in standard ES5, let me know or just run it through the online converter.
Oli c source share