docs
Loading...
Searching...
No Matches
JSInterop.h

Overview

Conversion functions and type traits connecting the DOM and JavaScript APIs.

#include <Ultralight/dom/JSInterop.h>

Note
This API is a preview and may still change after 2.0.

This header connects the DOM and JavaScript APIs so you can pass DOM elements between C++ and page script.

Convert elements between C++ and page script using the document's context:

js::Context ctx = dom::GetJSContext(document);
dom::Element hud = document.querySelector("#hud");
// Give page script an element:
ctx.GlobalObject()["hud"] = dom::ToJS(ctx, hud);
// Get the element a script returns:
dom::Element focused = dom::FromJS(
ctx.Evaluate("document.activeElement").value_or(js::Value()));

Elements in Bound Functions

Including this header specializes js::TypeTraits for dom::Element, letting bound functions accept and return elements directly. Passing null or undefined from JavaScript to a dom::Element parameter fails with a TypeError, so declare std::optional<dom::Element> to accept them.

Bind functions that take an element and an optional element:

js::API api("app");
api["highlight"] = [](dom::Element el) { el.classList.add("highlight"); };
api["clear"] = [](std::optional<dom::Element> el) {
if (el)
el->classList.remove("highlight");
};

Frame Contexts

An element converts to JavaScript only with the context of its own frame. Converting an element with a context from another frame or View returns an empty js::Value.

How you retrieve a context depends on the document's frame:

  • Main frame documents work with either js::Context(view) or dom::GetJSContext().
  • Subframe documents require dom::GetJSContext(). Passing a View to js::Context(view) wraps only the main frame.
Note
When JavaScript is disabled or a frame is sandboxed, dom::GetJSContext() returns an empty js::Context.
Note
This header is an opt-in include that isn't part of <Ultralight/DOM.h> or <Ultralight/JS.h>. When native code converts an element without including it, the compile error directs you to this file.
See also
dom::ToJS(), dom::FromJS(), dom::GetJSContext(), js::TypeTraits, js::Context

Classes

struct  TypeTraits< dom::Element >
 dom::Element as its JavaScript object. More...

Functions

js::Value ToJS (const js::Context &context, const Element &element)
 Get an element's JavaScript object (the same object the page's scripts see for it).
Element FromJS (const js::Value &value)
 Get the element a JavaScript value refers to (the inverse of ToJS()).
js::Context GetJSContext (const Document &document)
 Get the JavaScript context of a document (the context its page's scripts run in).

Namespaces

namespace  ultralight
 Root namespace for every public Ultralight type, function, and enumeration.
namespace  ultralight::dom
 Direct C++ access to modify page elements and handle events.
namespace  ultralight::js
 Type-checked JavaScript bridge between C++ and web pages.

Go to the source code of this file.