Open2
iframeとWindow.postMessage()を使ってオリジン間通信

通信のイメージ
localhost側のコード【送信】
post.html
<iframe
src="http://site.example:3000/reply.html"
onload="iframeLoaded()"
></iframe>
<script>
function iframeLoaded() {
const frame = document.querySelector("iframe");
frame.contentWindow.postMessage("Hello, Alice", frame.src);
}
window.addEventListener("message", (event) => {
if (event.origin !== "http://site.example:3000") {
return;
}
console.log(event.data);
});
</script>
site.example側のコード【受信と返信】
reply.html
<script>
window.addEventListener("message", (event) => {
if (event.origin !== "http://localhost:3000") {
return;
}
event.source.postMessage("Hello, Bob", event.origin);
});
</script>
↓
localhost:3000/post.html
を開くと、site.example/reply.html
から送られてきたHello, Bob
がコンソールに出力される

事前準備
- Expressでローカルサーバー起動 → npmを利用
- ホスト名の設定 → Macの場合は
/private/etc/hosts
に127.0.0.1 site.example
を追加
参考