Created
October 30, 2017 11:25
-
-
Save ssured/79471d3e78332e60567012969f716355 to your computer and use it in GitHub Desktop.
This file contains 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
<!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> |
This file contains 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
<!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