76 lines
2.0 KiB
HTML
76 lines
2.0 KiB
HTML
<!doctype html>
|
|
<html>
|
|
<head>
|
|
<title>Subscribe to events from pad.ma iframe embed</title>
|
|
</head>
|
|
<body>
|
|
<iframe width="640" height="360" src="http://pandora/documents/I/649,254,1289,723#embed" frameborder="0" allowfullscreen id="padembed"></iframe>
|
|
<button id="setUrl">
|
|
Set Iframe URL
|
|
</button>
|
|
<div id="messages">
|
|
|
|
</div>
|
|
<script>
|
|
|
|
const $iframe = document.getElementById('padembed');
|
|
|
|
/*
|
|
Listen to all messages received by iframes on the page.
|
|
*/
|
|
window.addEventListener('message', listener, false);
|
|
|
|
|
|
/*
|
|
Log all messages received from the iframe.
|
|
*/
|
|
function listener(event) {
|
|
const data = JSON.parse(event.data);
|
|
if (data.event === 'init') document.getElementById(data.target).isInit = true;
|
|
console.log('received event', event);
|
|
const $message = document.createElement('div');
|
|
$message.innerHTML = event.data;
|
|
document.getElementById('messages').appendChild($message);
|
|
}
|
|
|
|
|
|
/*
|
|
Event handler for clicking on button to set the URL of the iframe.
|
|
*/
|
|
document.getElementById('setUrl').addEventListener('click', function(e) {
|
|
console.log('clicked button');
|
|
$iframe.contentWindow.postMessage(JSON.stringify({
|
|
data: {
|
|
url: '/A/editor/00:00:55.800#embed'
|
|
},
|
|
event: 'seturl'
|
|
}), '*');
|
|
});
|
|
|
|
$iframe.addEventListener('load', () => {
|
|
let timeout;
|
|
|
|
/*
|
|
We can't be sure that the JS inside the iframe will be fully loaded and ready to receive messages. Therefore, we need to keep resending the init event until we are sure we've received the acknowledgement reply from the embed. This function calls itself every 250ms until `isInit` on the iframe object is set to true. The listener above sets this to true once it received the init acknowledgement.
|
|
*/
|
|
function init() {
|
|
console.log('init called');
|
|
if ($iframe.isInit) {
|
|
clearTimeout(timeout);
|
|
return;
|
|
}
|
|
$iframe.contentWindow.postMessage(JSON.stringify({
|
|
data: {
|
|
oxid: 'padembed'
|
|
},
|
|
event: 'init'
|
|
}), '*');
|
|
timeout = setTimeout(init, 250);
|
|
}
|
|
init();
|
|
});
|
|
</script>
|
|
</body>
|
|
|
|
</html>
|