Created
September 19, 2019 17:29
-
-
Save ryanmark/795ff1a9486e7fef5a560ce4129ebf82 to your computer and use it in GitHub Desktop.
Little helper module for building embeddable iframes that work with pym.js and AMP
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
const pym = require('pym.js') | |
const pymChild = window && window.pymChild ? window.pymChild : new pym.Child() | |
if ( window && !window.pymChild ) window.pymChild = pymChild | |
function sendHeight() { | |
// Tell pym and AMP to update the height | |
pymChild.sendHeight() | |
if ( window && window.parent ) | |
window.parent.postMessage({ | |
sentinel: 'amp', | |
type: 'embed-size', | |
height: document.body.scrollHeight | |
}, '*') | |
} | |
function sendReady() { | |
// Tell pym and AMP this embed is ready to be shown | |
pymChild.sendMessage('childLoaded', 'ready') | |
if ( window && window.parent ) | |
window.parent.postMessage({ | |
sentinel: 'amp', | |
type: 'embed-ready' | |
}, '*') | |
} | |
function getParentUrl() { | |
const match = window.location.search.match(/parentUrl=(https[^&]+)/) | |
if ( match && match.length === 2 ) return decodeURIComponent(match[1]) | |
} | |
function inAmp() { | |
return window.location.hash.match(/amp=1/) || window.location.search.match(/amp=1/) | |
} | |
function isIFramed() { | |
return window.self !== window.parent | |
} | |
module.exports = { | |
sendHeight: sendHeight, | |
sendReady: sendReady, | |
getParentUrl: getParentUrl, | |
inAmp: inAmp, | |
isIFramed: isIFramed | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment