0 votes
by (1.1k points)
edited by
I would like to ask what is the "window" function related to JS and how exactly do you use it.
Second question how to execute functions written in JS inside the twine. I have noticed that there are also Macro.add functions although there is no detailed and complete explanation of how to use JS in the twine...
I thank those who respond.

note: I appreciate if anyone knows some complete tutorial on this.

1 Answer

+1 vote
by (159k points)
selected by
Best answer

> what is the "window" object related to JS (not a function)

You can find the definition of this JavaScript object here at W3Schools and here at Mozilla Developer Network (MDN), but basically the object is used to programmatically access & maniputlate the properties of the current window / tab of the web-browser (tab). This object (and it's properties) is 'global' in scope / behaviour, and can be directly accessed in any script (and from the Console) at anytime.

eg. you can use the window.location property to determine the URL of the current HTML Document being shown in the window / tab.

/* Using a full reference. */
var url = window.location;

/* Using a partial reference. */
var url = location;

> how to execute functions written in JS inside SugarCube.

Custom JavaScript functions (and variables) defined within your project's Story Javascript area are added to that area's local scope, which means that by default such functions (and variables) can only be accessed by other JavaScript defined that area. 

There are a number of ways to elevate a custom function (or variable) to a 'global' like scope so that it can be access within the Passages of your project, one simple method is to define the function on the special setup object that is built into SugarCube's JavaScript engine.

eg. The following demostates one way to define a basic hello function on the setup object, the function uses an alert dialog to show a simple message. Place this code within your Story JavaScript area.

setup.hello = function() {
	alert("Hello world.");

Now that you have a 'global like' scoped function there are a number of ways you can use to execute it, which method you use depends on where exactly you want that function to be called from and what exactly the function does.

eg. One simple method is to use the <<run>> macro within a Passage.

<<link "Execute the Hello Function">>
	<<run setup.hello()>>