In this guide we will learn how to comunicate with nunu applications embeded inside a webpage using messages and how to use DOM elements to controll app content.
To communicate with the host webpage nunuStudio uses a message model system, where the host can send messages to the nunuStudio app and vice-versa, the messages are received using callback functions. To explore more about communication check the App API documentation.
To comunicate with the running application a message comunication model is used. The app or the page can send messages to each other that will be catched by callbacks used to process the information sent between them.
Its also possible to communicate between apps running on the same page, to achieve this we can pass the app objects from the page to the apps.
To send a message from the webpage to the nunuStudio aplication running the use the app.sendData(data) method. Data can be anything, assuming that the nunuApp is on the same JS context as the sender its possible send even object references.
To receive these messages inside the app we need to create a onAppData callback and to send data we use the sendDataApp function stored in the program object. The code bellow is a simple example when the nunuStudio app receives data is shows the data on the text object, and every time the key P is pressed the nunuStudio app send a test message to the host webpage.
var text, counter;
function initialize()
{
text = scene.getObjectByName("text");
counter = 0;
}
function update()
{
if(Keyboard.keyJustPressed(Keyboard.P))
{
program.sendDataApp("test" + counter);
}
}
function onAppData(data)
{
text.setText(data);
}
Before sending data from the nunu app to the webpage we need to define a onMessageReceive callback to process received messages. This callback can be defined as shown bellow, every time a message is send from the nunuStudio app to the webpage this function will be called.
//Send data to app
app.sendData("test text");
//Callback to receive data sent from the app
app.setOnDataReceived(function(data)
{
console.log("Received message from nunuStudio app", data);
});