Function Posted to HTML Element Not Working

When this code is embedded in an HTML element it works automatically:

<!DOCTYPE html>
<html>

<h2>JavaScript Functions</h2>

<p>This example calls a function which performs a calculation, and returns the result:</p>

<p id="demo"></p>

<script>
function myFunction(p1, p2) {
  return p1 * p2;
}
document.getElementById("demo").innerHTML = myFunction(4, 2);
</script>

</html>

However when it is posted to the element it goes not work automatically. The embedded code for the post is this:

<script>
window.onmessage = (event) => {

	if (event.data) {
		document.getElementById("GoogleSheetsDocs").innerHTML = event.data;
	}

};
</script>

The paragraphs are displayed but the function does not run. How can I get it to run when posted?

Hey there,

The first code snippet you input into the HTML element works because the script has a reference to the element ID demo in the html where the function is executing and being displayed on.

The non-working code is trying to set the event.data on the GoogleSheetDocs element ID but this element hasn’t been created so it has no reference. An element with that id needs to be created in your html.

Hope this helps you out

Best regards,