Skip to content

Instantly share code, notes, and snippets.

Created July 2, 2014 23:03
What would you like to do?
<!DOCTYPE html>
Copyright (c) 2013 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
<script type="text/javascript">
var JsonTutorialModule = null; // Global application object.
var msg = {
'action': 'sum',
'data': [2,4,11,13,23]
statusText = 'NO-STATUS';
function moduleDidLoad() {
JsonTutorialModule = document.getElementById('json_tutorial');
function handleMessage(message_event) {
function pageDidLoad() {
if (JsonTutorialModule == null) {
} else {
function updateStatus(opt_message) {
if (opt_message)
statusText = opt_message;
var statusField = document.getElementById('statusField');
if (statusField) {
statusField.innerHTML = statusText;
<body onload="pageDidLoad()">
<h1>NaCl C++ Tutorial: Getting Started</h1>
<div id="listener">
<script type="text/javascript">
var listener = document.getElementById('listener');
listener.addEventListener('load', moduleDidLoad, true);
listener.addEventListener('message', handleMessage, true);
<embed id="json_tutorial"
width=0 height=0
type="application/x-pnacl" />
<h2>Status <code id="statusField">NO-STATUS</code></h2>
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/var.h"
#include <sstream>
#include "json/json.h"
class JsonTutorialInstance : public pp::Instance {
explicit JsonTutorialInstance(PP_Instance instance) : pp::Instance(instance)
virtual ~JsonTutorialInstance() {}
virtual void HandleMessage(const pp::Var& var_message) {
Json::Value root; // will contains the root value after parsing.
Json::Reader reader;
// try to parse message
if (!reader.parse(var_message.AsString(), root)) {
// report to the user that it failed and where it failed
std::stringstream error_message_stream("Failed to parse JSON: ");
error_message_stream << reader.getFormatedErrorMessages();
send_json("error", error_message_stream.str());
// our root has to be an object (like JavaScript object or associative array in other languages)
if (!root.isObject()) {
send_json("error", "invalid data structure");
// second parameter is default value
const std::string action = root.get("action", "unknown").asString();
Json::Value data = root["data"];
if (action == "sum" && data.isArray()) {
int sum = 0;
for (uint32_t i=0; i < data.size(); i++) {
sum += data[i].asInt();
send_json("ok", Json::Int(sum));
} else {
send_json("error", "unknown action");
void send_json(const char *status, Json::Value response_data) {
// Json::Value is wrapper structure around any data (object, array, number, string)
// we're passing to its constructor Json::objectValue which creates basically a JavaScript object
// or associative array if you want
Json::Value response = Json::Value(Json::objectValue);
response["status"] = status; // like in any other language, create key and assign in value
response["response"] = response_data;
Json::FastWriter writer; // object that converts Json::Value into it's JSON string representation
std::string json_output = writer.write(response);
// wrap C++ string with Var object used by ppapi and send it to JavaScript
class JsonTutorialModule : public pp::Module {
JsonTutorialModule() : pp::Module() {}
virtual ~JsonTutorialModule() {}
virtual pp::Instance* CreateInstance(PP_Instance instance) {
return new JsonTutorialInstance(instance);
namespace pp {
Module* CreateModule() {
return new JsonTutorialModule();
} // namespace pp
# Copyright (c) 2013 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# GNU Make based build file.  For details on GNU Make see:
# Get pepper directory for toolchain and includes.
# If NACL_SDK_ROOT is not set, then assume it can be found three directories up.
THIS_MAKEFILE := $(abspath $(lastword $(MAKEFILE_LIST)))
NACL_SDK_ROOT ?= $(abspath $(dir $(THIS_MAKEFILE))../..)
# Project Build flags
WARNINGS := -Wno-long-long -Wall -Wswitch-enum -pedantic -Werror
CXXFLAGS := -pthread -std=gnu++98 $(WARNINGS)
# Compute tool paths
GETOS := python $(NACL_SDK_ROOT)/tools/
OSHELPERS = python $(NACL_SDK_ROOT)/tools/
OSNAME := $(shell $(GETOS))
PNACL_TC_PATH := $(abspath $(NACL_SDK_ROOT)/toolchain/$(OSNAME)_pnacl)
PNACL_CXX := $(PNACL_TC_PATH)/bin/pnacl-clang++
PNACL_FINALIZE := $(PNACL_TC_PATH)/bin/pnacl-finalize
LDFLAGS := -L$(NACL_SDK_ROOT)/lib/pnacl/Release -lppapi_cpp -lppapi -ljsoncpp
# Disable DOS PATH warning when using Cygwin based tools Windows
CYGWIN ?= nodosfilewarning
export CYGWIN
# Declare the ALL target first, to make the 'all' target the default build
all: json_tutorial.pexe
$(RM) json_tutorial.pexe json_tutorial.bc
$(PNACL_CXX) -o $@ $< -O2 $(CXXFLAGS) $(LDFLAGS)
json_tutorial.pexe: json_tutorial.bc
$(PNACL_FINALIZE) -o $@ $<
# Makefile target to run the SDK's simple HTTP server and serve this example.
HTTPD_PY := python $(NACL_SDK_ROOT)/tools/
.PHONY: serve
serve: all
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment