I have a story in an iframe, inside a parent page in wordpress.
I would like to take the variables that are on the parent page (wordpress), to run actions in the story inside iframe.
It is possible?
Both are on the same server and domain.
//In Wordpress parent page
var coins = 100;
var wallet = 500;
//In iframe with the story (#iframeid)
<< set parentcoins = coins >>
<< set parentwallet = wallet >>
<<set total = $parentcoins + $parentwallet >>
Your total: $total
I imagine that one of the processes could be using State.variables, but the problem is the iframe reading what is on the parent page.
pass the values as URL Parameters appended to the URL assigned to the src attribute of the <iframe> containing the ‘child’ page, and then that ‘child’ page can use JavaScript to process its window.location property to extract those values. One general example of this method can be found here.
use the window.postMessage() function to send a message containing the values to the ‘child’ page, which the ‘child’ page would listen for and process as required.
The following JavaScript code is one example of how to translate the example found in the StackOverFlow link I provided earlier into something that would work within SugarCube. This code needs to be placed within your project’s Story JavaScript area, and it makes use of the setup special object and the State.variables collection object.
/* Returns the value associated with a URL Parameter. */
setup.getParamValue = function (paramName) {
/* Default value to return if Paramenter is not found. */
var value = "";
/* get rid of "?" in querystring */
var url = window.location.search.substring(1);
/* get key-value pairs */
var pairs = url.split('&');
for (var i = 0; i < pairs.length; i++) {
/* split key and value */
var pair = pairs[i].split('=');
if (pair[0] === paramName) {
value = pair[1];
break;
}
}
return value;
};
/* Assign URL Parameters to Story Variables $param1 and $param2. */
State.variables.param1 = setup.getParamValue('param1');
State.variables.param2 = setup.getParamValue('param2');
Assuming your Story HTML file is named adventure.html, and the 2 parameters are named param1 and param2, then the URL used as the src of the <iframe> would look something like…