Last active
January 10, 2020 12:11
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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