How to integrate this Javascript code with Harlowe?

Twine Version: 2.3.9
Story Format: Harlowe 2.1.0

Hi,

I’m a college student working on a project. I have a passage where I’d like to integrate a bit of Javascript with Harlowe to be able to execute a function. I’m currently doing this but it doesn’t work:

x—Passage Begin—x

<spa.n div=“img-pop”>Click me.</spa.n>

<sc.ript>
$(“img-pop”).click(function() {
window.top.postMessage(‘hello’, ‘*’);
});
</sc.ript>

x—Passage End—x

I want to click “click me”, so that the twine HTML file sends a message to a parent HTML file that I’m embedding it in, but the code simply doesn’t work. Also, excuse the “spa.n” and “sc.ript” - I’ve put in the periods there to prevent the editor from treating them as actual web elements here. I have a tight deadline for this project, so I’d really appreciate your help on this!

To ensure your code isn’t mangled, use the “</>” button for Preformatted Text and paste it into there. Then things won’t get messed up by the forum.

Based on the copy/paste there are a number of errors such as <sc.ript>>, </scr.ipt>, and <spa.n> which have extra periods there. I don’t think that is supposed to be there.

@Chapel has a Macro framework for Harlowe that might help as well.

The CSS selector you are using in your jQuery $('img-pop') call isn’t going to locate the div="img-pop" property of your <span> example, I will assume you meant:

  1. the <span> to have either an id="img-pop" or a class="img-pop" property.
  2. the jQuery CSS selector to be either $(’#img-pop’) or $('.img-pop').

Using the window.postMessage() method’s documentation as a guide placing code like the following within the Passage of a Harlowe based project…

<span id='img-pop'>Click me.</span>

<script>
$('#img-pop').click(function() {
	window.parent.postMessage('hello', '*');
});
</script>

…which was then compiled into a Story HTML file named message-test.html successful posted a message to a parent HTML file like the following, that used an <iframe> element to include the Story HTML file.

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>IFrame test for Harlowe</title>
	<script>
		function receiveMessage(event) {
			console.log('received message: event-data: ' + event.data);
		}
		window.addEventListener("message", receiveMessage, false);
	</script>
</head>
<body>
	<iframe src="message-test.html" frameborder="0" width="640px" height="480px"></iframe>
</body>
</html>