In my HTML
Let's say I have 2 input fields with values 3 and 4:
<form onchange="reload()">
<h2>Input:</h2>
<input type="number" id="val1" name="val1" value="3">
<input type="number" id="val2" name="val2" value="4">
<br><br>
<h2>Output</h2>
<input type="text" id="out" name="out" value="untouched by C++"><br>
</form>
In my JavaScript
I get the two values and push them into an array like so:
Module = document.getElementById('module');
var msg = [];
msg.push(Number(document.getElementById('val1').value));
msg.push(Number(document.getElementById('val2').value));
Then I send it to my C++ file to process the message
Module.postMessage(msg);
In my C++ file [ Here is where I am stuck. ]
The code I have to handle the message is below
virtual void HandleMessage(const pp::Var& var_message) {
std::string message = var_message.AsString();
pp::Var var_reply = pp::Var(message);
PostMessage(var_reply);
}
The issue is that it handles a string [actually it crashes if I my msg is of type of an array].
What I want it to expect and accept is an array or an object.
Basically, something like this:
virtual void HandleMessage(const pp::Var& var_message) {
pp::Var var_reply = var_message[0] + var_messgae[1]; // I expect this to be 3+4=7
PostMessage(var_reply);
}
I have resolved the issue I had. The best approach is to use an object and pass the values as a JSON object, so
in JavaScript
values = {
"val1": Number(document.getElementById('val1').value),
"val2": Number(document.getElementById('val2').value)
};
msg = JSON.stringify(values);
Module.postMessage(msg);
Then handle the message and send the response back to JavaScript
in C++:
In the header you need to add picoJSON to handle JSON and sstream to work with isstringstream:
#include <sstream>
#include "picojson.h"
using namespace std;
then later in the code:
virtual void HandleMessage(const pp::Var& var_message) {
picojson::value v;
// pass the message that was sent from JavaScript as a string
// var_message.AsString() will be in form "{\"val1\":4,\"val2\":4}");
// and convert it to istringstream
istringstream iss2((string)var_message.AsString());
// parse iss2 and extract the values val1 and val2
string err = picojson::parse(v, iss2);
int val1 = (int)v.get("val1").get<double>();
int val2 = (int)v.get("val2").get<double>();
// finally send the message and you'll see the sum in the JavaScript
PostMessage( val1 + val2 );
}