Skip to content

Instantly share code, notes, and snippets.

@ssured
Created October 30, 2017 11:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ssured/79471d3e78332e60567012969f716355 to your computer and use it in GitHub Desktop.
Save ssured/79471d3e78332e60567012969f716355 to your computer and use it in GitHub Desktop.
<!doctype html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/comlinkjs/comlink.global.js"></script>
<script>
const api = {
add(a,b){
return new Promise(resolve => resolve({result: a + b}));
}
};
async function connectParentApi(parent) {
let handshake;
const handshakePromise = new Promise(resolve => handshake = resolve)
Comlink.expose({...api, handshake}, parent);
const parentApi = Comlink.proxy(parent);
await handshakePromise;
console.log(`2 * 3 = `, await parentApi.mult(2, 3));
return parentApi;
}
connectParentApi(window.parent);
</script>
</head>
<body>
<h1>Frame</h1>
</body>
</html>
<!doctype html>
<script src="https://cdn.jsdelivr.net/npm/comlinkjs/comlink.global.js"></script>
<script>
const api = {
mult(a,b){
return new Promise(resolve => resolve({result: a * b}));
}
};
async function connectChildApi(iframe) {
await new Promise(resolve => iframe.onload = resolve);
Comlink.expose(api, iframe.contentWindow);
const childApi = Comlink.proxy(iframe.contentWindow);
await childApi.handshake();
console.log(`1 + 3 = `, await childApi.add(1, 3));
return childApi;
}
window.onload = async () => {
const iframe = document.createElement('iframe');
iframe.setAttribute('src', 'iframe.html');
document.body.appendChild(iframe);
const childApi = await connectChildApi(iframe);
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment