Scripting between C++ and JavaScript
How a host calls into a page, how a page calls into the host, and how a game publishes data models.
A page and its host talk through a small set of entry points. Pick the one that matches the direction and how often it runs.
| Direction | Mechanism | Use it for |
|---|---|---|
| Host to page | callJavaScriptFunctionJson, callJavaScriptFunctionString | Pushing state into a function the page defines. No source is compiled per call. |
| Host to page | setDataModel and data-bind-* attributes | Declarative UI that follows a model. See Data models. |
| Host to page | executeJavaScript, executeJavaScriptRaw | One-off scripts, setup, diagnostics. |
| Host to page | evaluateJavaScript | A quick read of a value from the page. |
| Page to host | Native functions on the binder facade | A click, a choice, a request. Arguments arrive as strings. |
Scripts run in the view's selected engine, on the thread that calls tick(). The 26.08.0.1
Windows package uses V8 15.6.75.12. QuickJS and Hermes are being completed in source and are not part of
that package. For newer engine-labelled distributions, see Choose a JavaScript engine. Do not assume V8 inspector/debugger features exist in another backend. Read
view.getJavaScriptEngineName() to identify the running engine.
Keep every call in this table on that thread (see Threads). The host must initialize the JavaScript engine before running page script: see The order that works.
Run a script
const std::string source = "showDamage(" + std::to_string(amount) + ", "
+ std::to_string(x) + ", " + std::to_string(y) + ");";
view.executeJavaScriptRaw("damage-number", reinterpret_cast<const uint8_t*>(source.data()),
source.size());executeJavaScript(name, bytes, execNow) takes the script's name and its UTF-8 source. The name
appears in error messages and in DevTools. The engine does not look it up as a file. The call
compiles and runs the script before it returns. It has no return value, and the execNow
argument is not read. If V8 is not running it logs "No V8 isolate" and does nothing.
executeJavaScriptRaw(name, pointer, length, execNow) does the same with a pointer, so nothing
that owns memory crosses the DLL boundary. Use it when your engine replaces the global
operator new (Unreal does).
evaluateJavaScript(source, result) runs a script and gives back String(value). The result is
empty for undefined, null or a thrown error. Use it for occasional reads. It is not meant for a
per-frame hot path.
Call a function the page defines
Running a source string for every update compiles it every time. To push state each frame or each event, define a function in the page and call that:
window.hud = {
update(state) {
document.getElementById("health").textContent = state.health;
},
};view.callJavaScriptFunctionJson("hud.update", "{\"health\":72,\"ammo\":18}");callJavaScriptFunctionJson(name, json) finds a global function, or a dotted path such as
hud.update that it calls with its owner as this, and calls it with one argument. V8 parses the
JSON straight into a JavaScript value, so the page receives an object, not a string. Pass nullptr
to call it with no arguments. callJavaScriptFunctionString passes the argument as a string.
Both return true when the function was found and ran without throwing. A function the page has
not defined yet returns false and logs nothing, so you can call before the page is ready.
Call the host from the page
The package gives you a small, V8-free binder API in APHTML/Script/API/APUIBinderFacade.h. It
makes namespace.function(...) callable from script:
using namespace aperture::binder;
// Only for a view loading content trusted with this binder.
view.setNativeBinderAccessAllowed(true);
APUIBinder* binder = APUICreateBinder();
APUIAttachBinderToView(binder, &view);
APUIRequestNativeFunction(binder, "game", "playSound",
[](const std::vector<std::string>& args)
{
if (!args.empty())
PlaySound(args[0]);
});
view.loadHtmlFromFile("ui/index.html"); // the bindings are applied heregame.playSound("button-click");- Grant native-binder access only to trusted content; it is denied by default in the current engine source. See Security.
- Attach the binder, and request your functions, before the view loads a document. The engine applies them whenever the view builds a V8 context, which is the first load and every navigation after it.
- Every argument arrives as a string. A native function returns nothing to the page. To answer, call a function the page defines.
- The callback runs on whichever thread is running the page's script: the one that calls
tick(), the input functions orexecuteJavaScript. If that is your game thread, you have nothing to marshal. If the view lives on a separate UI thread, hand the call over to your game thread before you touch state that is not thread-safe. A C++ exception that escapes the callback becomes a JavaScript error at the call. - Binding the same namespace and name again replaces the callback.
APUIIsBinderFlushed(binder)tells you whether the bindings have been applied to a live context yet.- Destroy the view first, then call
APUIDestroyBinder. The view keeps a raw pointer to the binder.
console.log, console.warn and console.error from the page reach your logging system. See
Your own C++ host.
The templated binder
APUIBinder also has bindFunction, bindClass<T> with a ClassBinder<T> (constructor,
method, property), BindNamespacedFunction and RequestModuleToBind, which expose C++ classes
and free functions to script. The typed templates include V8's binding headers and require a matching V8 development
setup. Prefer APUIBinderFacade.h for the package's string-argument bridge; do not mix headers
or import libraries from another V8 build. Arguments and return values convert through aperture::binder::convert<T>,
which handles booleans, integers, floating-point numbers, enums, strings, tuples, variants,
arrays and maps of those, and classes you have bound.
APUIBinder has no model, property or event API, so there is no CreateModel or UpdateModel. Use
data models for state. APUIJSEvent, a publish and subscribe queue, ships in the
package, but the engine never creates one and no page can reach it, so nothing connects it to a
view.
Data models
A page can declare what shows a model, and the host pushes the model. The engine keeps the DOM in step:
<span data-bind-value="{{player.name}}"></span>
<div data-bind-if="{{player.alive}}">Alive</div>
<div class="bar" data-bind-style-width="{{player.hp + '%'}}"></div>
<ul data-bind-for="item of {{player.inventory}}">
<li>{{item.name}} x{{item.qty}}</li>
</ul>view.setDataModel("player", R"({"name":"Ada","hp":72,"alive":true,"inventory":[]})");setDataModel(name, json) parses the JSON in the page's context, makes it the JavaScript global
name, and re-evaluates every binding that references it. Each binding is a {{ ... }} expression
that runs in the page, over the model globals.
The directives are data-bind-value (text), data-bind-if (show or hide), data-bind-for
(repeat the markup inside the element for each item, with {{item...}} and {{index}} inside), data-bind-class
({low: {{player.hp < 30}}}), data-bind-attr-NAME, data-bind-style-NAME, data-bind-src,
data-bind-href and data-bind-checked. Data binding is the reference: it lists
what each directive does and the two rules that trip people up, which are that an expression has to begin with the model
name and that a list repeats its contents, so data-bind-for goes on the container.
| To do this | Call |
|---|---|
| Replace a model. This is the call for a host that publishes a model. | view.setDataModel("player", json) |
| Refresh after the page or host edited the object in place | view.notifyDataModelUpdated("player") |
| Refresh a model and restyle the elements bound to it | view.notifyModelUpdated("player") |
| Re-evaluate every binding | view.synchronizeAllBindings() |
Find data-bind-* attributes again after the DOM changed a lot | view.rescanDataBindings() |
| From the page: edit in place, then refresh | player.hp -= 5; ApertureDataBind.update("player") |
| From the page: replace and refresh | ApertureDataBind.set("player", newObject) |
| From the page: rescan the DOM | ApertureDataBind.rescan() |
The DOM from C++
getDomDocument() and getDomWindow() return the document and window objects. The 26.08.0.1
package includes the DOM and animation headers, including APHTML/Animation/AnimationEasing.h;
the earlier missing-header limitation no longer describes this release. Include
APHTML/DOM/DOMDocument.h and APHTML/DOM/DOMElement.h before using element methods.
Keep element access on the view's owning thread and release handles before destroying the view.
For most HUD updates, publishing a model or calling a page function keeps the host interface small.