Skip to content

Instantly share code, notes, and snippets.

@klipstein
Last active January 10, 2020 12:11
Show Gist options
  • Save klipstein/364150c15fc76ea629b7a0c9f5625d03 to your computer and use it in GitHub Desktop.
Save klipstein/364150c15fc76ea629b7a0c9f5625d03 to your computer and use it in GitHub Desktop.
Get top-most URL from within an iFrame. It either uses the referrer or the current location.
export default getUrl;
function getUrl(window) {
const topMostWindow = getTopMostIframeWithReferrer(window);
const { referrer } = topMostWindow.document;
if (!isInIframe(window)) return window.location.href;
// in Firefox it won't fill the referrer for friendly iframes
if (referrer === '' && isParentFrameFriendly(topMostWindow)) {
return topMostWindow.parent.location.href;
}
return referrer || '';
}
function getTopMostIframeWithReferrer(window) {
if (isInIframe(window)) {
if (isParentFrameFriendly(window) && !isParentFrameTop(window)) {
return getTopMostIframeWithReferrer(window.parent);
}
}
return window;
}
function isParentFrameFriendly(window) {
try {
return !!window.parent.document;
} catch (e) {
return false;
}
}
function isParentFrameTop(window) {
try {
return window.parent === window.top;
} catch (e) {
return false;
}
}
// taken from http://stackoverflow.com/questions/326069
function isInIframe(window) {
try {
return window.self !== window.top;
} catch (e) {
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment