Skip to content

Instantly share code, notes, and snippets.

@samwx
Last active June 14, 2019 04:17
Show Gist options
  • Save samwx/cd5b636b536ab10d678f03fc490210b7 to your computer and use it in GitHub Desktop.
Save samwx/cd5b636b536ab10d678f03fc490210b7 to your computer and use it in GitHub Desktop.
Micro frontend presentation
init(): void {
this.handleOnReceiveMessage = this.onReceiveMessage.bind(this)
window.addEventListener('message', this.handleOnReceiveMessage)
}
onReceiveMessage(message: MessageEvent) {
const action = message.data
switch(action) {
case 'a':
doThis();
break;
case 'b':
doThat();
break;
default:
throw new Error('Unrecognized action')
}
}
// /about page
<div id="container">
<iframe src="https://about.project.com"></iframe>
</div>
// /products page
<div id="container">
<iframe src="https://products.project.com"></iframe>
</div>
{
"name": "@my-project/main",
"version": "1.0.0",
"description": "My amazing application",
"dependencies": {
"@my-project/frontend-1": "1.0.0",
"@my-project/frontend-2": "1.0.0",
"@my-project/frontend-3": "1.0.0",
}
}
/**
* Send message to parent iframe or to specified window
* @param payload
* @param element
*/
public sendMessage(payload: IMessagePayload): Promise<any> {
const message = this.formatPayload(payload)
const deferred = createDeferred()
this.createPromiseCache(message.trackingProperties.id, deferred)
this.targetWindow.postMessage(message, '*')
return deferred.promise
}
<script src="https://about.project.com/bundle.js"></script>
<script src="https://products.project.com/bundle.js"></script>
// /about page
<div id="container">
<about-micro-frontend></about-micro-frontend>
</div>
// /products page
<div id="container">
<products-micro-frontend></products-micro-frontend>
</div>
// /about page
<div id="container">
<about-micro-frontend></about-micro-frontend>
</div>
// /products page
<div id="container">
<products-micro-frontend></products-micro-frontend>
</div>
{
"name": "@my-project/web-components",
"version": "1.0.0",
"description": "My amazing application",
"dependencies": {
"@my-project/about-micro-frontend": "1.0.0",
"@my-project/products-micro-frontend": "1.0.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment