Skip to content

Instantly share code, notes, and snippets.

@zipang
Created September 30, 2022 09:15
Show Gist options
  • Save zipang/4f835c77ec35f9b3a72b052cc4bd636e to your computer and use it in GitHub Desktop.
Save zipang/4f835c77ec35f9b3a72b052cc4bd636e to your computer and use it in GitHub Desktop.
IFRAME MESSAGES SENDER

IFRAME MESSAGES SENDER

This codepen is used to be embedded and show how to send message to its parent page

A Pen by zipang on CodePen.

License.

<div class="container">
<h1>1 AM NOT YOUR STANDARD IFRAM3</h1>
<button id="cmdSendRandomQuote" class="basic-button">
Click here to receive some random quote
</button>
<button id="cmdGiveRandomBeer" class="basic-button">
Click here to have some beer
</button>
<h2>Last message sent</h2>
<p><ode><pre id="lastMessage"></pre></code></p>
</div>
const lastMessage = document.getElementById("lastMessage");
const postMessageFrom = (apiUrl) => (evt) => {
fetch(apiUrl)
.then((resp) => resp.json())
.then((randomData) => {
console.log("Sending", randomData);
window.parent.postMessage(JSON.stringify(randomData), "https://cdpn.io/zipang");
lastMessage.innerHTML = JSON.stringify(randomData, null, ' ');
});
};
document
.getElementById("cmdSendRandomQuote")
.addEventListener(
"click",
postMessageFrom("https://dummyjson.com/quotes/random")
);
document
.getElementById("cmdGiveRandomBeer")
.addEventListener(
"click",
postMessageFrom("https://random-data-api.com/api/v2/beers")
);
* {
font-family: serif;
}
.container {
max-width: 60ch;
margin: 0 auto;
min-height: 100vh;
}
.basic-button {
padding: 1em;
margin: 1em auto;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment