JSFiddle - React, Tailwind, and code Playground
by velo_ninja
HTML
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function init() {
// when a message is received from the page code
window.onmessage = (event) => {
if (event.data) {
console.log("HTML Code Element received a message!");
insertMessage(event.data);
}
}
}
// display received message
function insertMessage(msg) {console.log('Insert running...');
document.getElementById('demo').innerHTML = msg;
var myText = document.getElementById('demo').innerHTML;
sendReturnMessage(myText);
}
// function to be called when the button is pressed
function sendMessageToOuterElement() {console.log('Button pressed...')
var myText = document.getElementById('demo').innerHTML;
sendReturnMessage(myText);
}
// send message to the page code
function sendReturnMessage(msg) {console.log('MSG: ', msg);
window.parent.postMessage(msg, "*");
}
</script>
</head>
<body onload="init();" style="background-color:lightgray;">
<h1>HTML Component Test</h1>
<p id="demo">Message will go here</p>
<!-- Button to send a message to the outer element -->
<button id='xxx'>Send Message</button>
<script>
// Corrected the method name to add an event listener to the button
var myButton = document.getElementById('xxx');
myButton.addEventListener('click', sendMessageToOuterElement);
</script>
</body>
</html>