docs
Loading...
Searching...
No Matches
Context

#include <Ultralight/js/Context.h>

Overview

JavaScript execution environment for a page.

Every call into a page's JavaScript environment goes through its Context. It represents the execution state of a loaded document, providing access to the global object where page functions and variables live.

Construct a Context from a View inside LoadListener::OnDOMReady() to call functions and read global variables on the page:

void MyApp::OnDOMReady(View* caller, uint64_t frame_id, bool is_main_frame,
const String& url) {
if (!is_main_frame)
return;
js::Context ctx(caller);
ctx["ShowMessage"]("Howdy!"); // call a page function
double score = js::Or(ctx["score"], 0.0); // read a global (0.0 if it fails)
double doubled = js::Or(ctx.Evaluate<double>("score * 2"), 0.0);
}
Unicode string container with conversions for UTF-8, UTF-16, and UTF-32.
Definition String.h:31
Web-page container rendered to an offscreen surface.
Definition View.h:483
JavaScript execution environment for a page.
Definition Context.h:151
T Or(const Value &value, T fallback)
Convert a value to a C++ type with a fallback (the free-function form of Value::Or()).
Definition Value.h:1220

Getting a Context

Constructing a Context with a View wraps the main frame's JavaScript environment. To access the Context of a subframe or a specific document, pass that document to dom::GetJSContext().

You'll typically construct a Context inside a LoadListener callback:

Each page gets its own Context. When a View navigates to a new page, the old Context's page is gone, along with every Value created from it (see js::Value for what that means), so you'll need to obtain a new Context for the new page. Operations on a Context whose page is gone fail safely instead of crashing.

Creating Values

Call Make() to convert a native C++ value into a JavaScript Value. The method converts any type that js::TypeTraits supports, including numbers, strings, standard containers, reflected structs, and enums.

Convert a reflected struct to a JavaScript object and pass it to a page function:

struct HudSettings {
std::string theme;
double volume;
};
js::Value settings = ctx.Make(HudSettings { "dark", 0.8 });
ctx["applySettings"](settings);
A handle to a live JavaScript value.
Definition Value.h:210
Note
Context operations must run on the Renderer's thread. To dispatch work from another thread, call PostTask() to schedule a callback that runs during a later Renderer::Update().
Note
js::Context and dom::data::Context are unrelated types (dom::data::Context manages declarative data bindings).
See also
js::Value, js::CallInfo::context(), dom::GetJSContext(), LoadListener::OnDOMReady()

Static Public Member Functions

static Context Adopt (ULJSContext handle)
 Take ownership of a context handle from the C API.
static Context FromBorrowed (ULJSContext handle)
 Add a reference to a context handle the library owns (eg, the context a C API callback receives) so you can use it with this class and keep it after the callback.

Public Member Functions

 Context ()=default
 Create an empty Context.
 Context (View *view)
 Get the context of a View's main frame.
 Context (const Value &value)
 Get the context a value belongs to.
 Context (const Context &other)
 Copy constructor (refers to the same context).
 Context (Context &&other) noexcept
 Move constructor (other becomes empty).
Context & operator= (Context other) noexcept
 Assignment (copies or moves other into this Context).
 ~Context ()
 Destructor (releases this handle).
 operator bool () const
 Whether or not this Context is valid (it isn't empty and its page is still alive).
bool IsEmpty () const
 Whether or not this Context holds nothing.
bool IsAlive () const
 Whether or not this Context's page is still alive (the same test as operator bool).
Result< Value > Evaluate (std::string_view script, const char *source_url=nullptr) const
 Run a script and get its completion value.
template<typename T>
requires Marshalable<T>
Result< T > Evaluate (std::string_view script, const char *source_url=nullptr) const
 Run a script and convert its completion value to a C++ type (see Value::To()).
Value GlobalObject () const
 Get the global object.
Value::Ref operator[] (const char *name) const
 Access a property of the global object (ctx["fn"](args) is the same as ctx.GlobalObject()["fn"](args)):
template<typename T>
Value Make (T &&value) const
 Convert a C++ value to a JavaScript value through js::TypeTraits.
Value MakeObject () const
 Create a new empty JavaScript object.
Value MakeArray (const Value *elements, size_t count) const
 Create a new JavaScript Array.
Value MakeArray (std::initializer_list< Value > elements) const
 Create a new JavaScript Array from a brace list (eg, ctx.MakeArray({ a, b })).
Value MakeArray (std::span< const Value > elements) const
 Create a new JavaScript Array from a range (eg, a std::vector<js::Value>).
Result< Value > MakeFromJSON (std::string_view json) const
 Create a value from JSON text (the reverse of Value::ToJSON()):
template<typename F>
void PostTask (F &&task) const
 Run a function with this context during a later Renderer::Update().
PendingPromise MakePromise () const
 Create a pending Promise and the Resolver that settles it, to hand a Promise to the page outside a bound function:
ArrayBuffer MakeArrayBuffer (const RefPtr< ultralight::Buffer > &buffer) const
 Create an ArrayBuffer that shares a Buffer's bytes with JavaScript without copying.
ArrayBuffer MakeArrayBuffer (const void *bytes, size_t length) const
 Create an ArrayBuffer holding a copy of the given bytes.
template<typename T>
TypedArray< T > MakeTypedArray (size_t length) const
 Create a typed array of zero-filled elements of type T (eg, MakeTypedArray<float>(4) creates a Float32Array; see js::TypedArray for the element types).
template<typename T>
TypedArray< T > MakeTypedArray (const RefPtr< ultralight::Buffer > &buffer) const
 Create a typed array of elements of type T that shares a Buffer's bytes with JavaScript without copying.
template<typename Fn>
Value MakeFunction (const char *name, Fn &&fn) const
 Create a JavaScript function backed by a C++ callable, to hand to the page (eg, as a callback).
HandleStats GetHandleStats () const
 Count the live handles on this context, for finding leaks.
ULJSContext raw () const
 Get the C API handle without transferring ownership.
ULJSContext LeakRef ()
 Give up ownership of the C API handle and return it.

Constructor & Destructor Documentation

◆ Context() [1/5]

Context ( )
default

Create an empty Context.

◆ Context() [2/5]

Context ( View * view)
inlineexplicit

Get the context of a View's main frame.

Parameters
viewThe View. The Context is empty if view is NULL or its page can't run script (JavaScript is disabled or the document is sandboxed).
Note
A Context belongs to the page loaded now. After the View loads a new page, get a new Context.

◆ Context() [3/5]

Context ( const Value & value)
inlineexplicit

Get the context a value belongs to.

Parameters
valueThe value. An empty Value gives an empty Context, and a Value whose page is gone gives a Context whose page is also gone.

◆ Context() [4/5]

Context ( const Context & other)
inline

Copy constructor (refers to the same context).

◆ Context() [5/5]

Context ( Context && other)
inlinenoexcept

Move constructor (other becomes empty).

◆ ~Context()

~Context ( )
inline

Destructor (releases this handle).

Member Function Documentation

◆ Adopt()

Context Adopt ( ULJSContext handle)
inlinestatic

Take ownership of a context handle from the C API.

Parameters
handleThe handle to take ownership of.
Returns
Returns a Context that owns handle.
Warning
Don't pass a handle the library owns (eg, one a callback receives). Use FromBorrowed() for that.

◆ Evaluate() [1/2]

template<typename T>
requires Marshalable<T>
Result< T > Evaluate ( std::string_view script,
const char * source_url = nullptr ) const
inlinenodiscard

Run a script and convert its completion value to a C++ type (see Value::To()).

js::Result<double> health = ctx.Evaluate<double>("game.player.health");
double speed = ctx.Evaluate<double>("game.player.speed").value_or(1.0);
Expected< T, Error > Result
The result of a JavaScript operation that can fail: a T or a js::Error.
Definition Error.h:520
Parameters
scriptThe script (UTF-8; embedded null characters are kept).
source_urlA URL for the script, used in error reports (may be NULL).
Returns
Returns the converted value. Fails with a JavaScript exception if the script throws, or with a TypeError if the value doesn't convert to T.

◆ Evaluate() [2/2]

Result< Value > Evaluate ( std::string_view script,
const char * source_url = nullptr ) const
inlinenodiscard

Run a script and get its completion value.

Parameters
scriptThe script (UTF-8; embedded null characters are kept).
source_urlA URL for the script, used in error reports (may be NULL).
Returns
Returns the script's completion value. Fails with a JavaScript exception if the script throws.

◆ FromBorrowed()

Context FromBorrowed ( ULJSContext handle)
inlinestatic

Add a reference to a context handle the library owns (eg, the context a C API callback receives) so you can use it with this class and keep it after the callback.

Parameters
handleThe borrowed handle.
Returns
Returns a Context with its own reference to handle.

◆ GetHandleStats()

HandleStats GetHandleStats ( ) const
inline

Count the live handles on this context, for finding leaks.

Value handles you never destroy keep counting after the page goes away.

Returns
Returns the counts (all zero for an empty Context).
See also
HandleStats

◆ GlobalObject()

Value GlobalObject ( ) const
inline

Get the global object.

Returns
Returns the global object (an empty Value if the context is gone).

◆ IsAlive()

bool IsAlive ( ) const
inline

Whether or not this Context's page is still alive (the same test as operator bool).

Note
Safe to call from any thread, but off the Renderer's thread the result may already be out of date when you act on it.

◆ IsEmpty()

bool IsEmpty ( ) const
inline

Whether or not this Context holds nothing.

◆ LeakRef()

ULJSContext LeakRef ( )
inline

Give up ownership of the C API handle and return it.

Returns
Returns the handle. You must call ulDestroyJSContext() when finished.

◆ Make()

template<typename T>
Value Make ( T && value) const
inline

Convert a C++ value to a JavaScript value through js::TypeTraits.

This works for every supported type, including reflected structs, enums, containers, js::null, and js::undefined.

Parameters
valueThe C++ value to convert.
Returns
Returns the new value (an empty Value if the context is gone).

◆ MakeArray() [1/3]

Value MakeArray ( const Value * elements,
size_t count ) const
inline

Create a new JavaScript Array.

Parameters
elementsThe elements (an empty Value becomes undefined).
countThe number of entries in elements.
Returns
Returns the new Array (an empty Value if the context or an element's page is gone).

◆ MakeArray() [2/3]

Value MakeArray ( std::initializer_list< Value > elements) const
inline

Create a new JavaScript Array from a brace list (eg, ctx.MakeArray({ a, b })).

Parameters
elementsThe elements.
Returns
Returns the new Array (an empty Value if the context or an element's page is gone).

◆ MakeArray() [3/3]

Value MakeArray ( std::span< const Value > elements) const
inline

Create a new JavaScript Array from a range (eg, a std::vector<js::Value>).

Parameters
elementsThe elements.
Returns
Returns the new Array (an empty Value if the context or an element's page is gone).

◆ MakeArrayBuffer() [1/2]

ArrayBuffer MakeArrayBuffer ( const RefPtr< ultralight::Buffer > & buffer) const
inline

Create an ArrayBuffer that shares a Buffer's bytes with JavaScript without copying.

The ArrayBuffer keeps a reference to buffer until it's garbage collected or detached (see "Byte Lifetimes" on js::ArrayBuffer).

Parameters
bufferThe buffer to share. An empty buffer gives an ordinary empty ArrayBuffer that keeps no reference.
Returns
Returns a new ArrayBuffer over the buffer's bytes (an empty wrapper if buffer is null or the context is gone).

◆ MakeArrayBuffer() [2/2]

ArrayBuffer MakeArrayBuffer ( const void * bytes,
size_t length ) const
inline

Create an ArrayBuffer holding a copy of the given bytes.

Parameters
bytesThe bytes to copy (may be NULL only when length is 0).
lengthThe number of bytes to copy (0 creates an empty ArrayBuffer).
Returns
Returns a new ArrayBuffer (an empty wrapper if bytes is NULL and length isn't 0, or if the context is gone).

◆ MakeFromJSON()

Result< Value > MakeFromJSON ( std::string_view json) const
inlinenodiscard

Create a value from JSON text (the reverse of Value::ToJSON()):

js::Value config = js::OrEmpty(ctx.MakeFromJSON(R"({"volume": 5, "muted": false})"));
T OrEmpty(Result< T > result)
Get a Result's value, or a default-constructed T if it holds an error.
Definition Error.h:539
Parameters
jsonThe JSON text (any JSON value).
Returns
Returns the new value. Fails with a SyntaxError (a JavaScript exception) if the JSON is invalid.

◆ MakeFunction()

template<typename Fn>
Value MakeFunction ( const char * name,
Fn && fn ) const
inline

Create a JavaScript function backed by a C++ callable, to hand to the page (eg, as a callback).

Arguments convert the same way as for a js::API binding:

js::Value cb = ctx.MakeFunction("onTick", [](double dt) { ... });
Parameters
nameThe function's name, also used in its conversion errors.
fnThe callable.
Returns
Returns the function (an empty Value if the context is gone).
Note
Only synchronous callables work here (returning a value or a js::Result). Bind async functions (a js::Task or a trailing js::Resolver) through js::API.
Note
The callable is destroyed on the Renderer's thread after the function is garbage collected.

◆ MakeObject()

Value MakeObject ( ) const
inline

Create a new empty JavaScript object.

Returns
Returns the new object (an empty Value if the context is gone).

◆ MakePromise()

PendingPromise MakePromise ( ) const
inline

Create a pending Promise and the Resolver that settles it, to hand a Promise to the page outside a bound function:

auto [promise, resolver] = ctx.MakePromise();
ctx["ready"] = promise;
// later, from any thread:
resolver.Resolve(std::string("ok"));
Returns
Returns the Promise and its Resolver (both empty if the context is gone).

◆ MakeTypedArray() [1/2]

template<typename T>
TypedArray< T > MakeTypedArray ( const RefPtr< ultralight::Buffer > & buffer) const
inline

Create a typed array of elements of type T that shares a Buffer's bytes with JavaScript without copying.

Lifetime works as for MakeArrayBuffer().

Parameters
bufferThe buffer to share (its size must be a multiple of sizeof(T)). An empty buffer gives an ordinary empty typed array that keeps no reference.
Returns
Returns a new TypedArray over the buffer's bytes (an empty wrapper if buffer is null, its size isn't a multiple of sizeof(T), or the context is gone).

◆ MakeTypedArray() [2/2]

template<typename T>
TypedArray< T > MakeTypedArray ( size_t length) const
inline

Create a typed array of zero-filled elements of type T (eg, MakeTypedArray<float>(4) creates a Float32Array; see js::TypedArray for the element types).

Parameters
lengthThe number of elements (not bytes).
Returns
Returns a new TypedArray (an empty wrapper if the context is gone).

◆ operator bool()

operator bool ( ) const
inlineexplicit

Whether or not this Context is valid (it isn't empty and its page is still alive).

◆ operator=()

Context & operator= ( Context other)
inlinenoexcept

Assignment (copies or moves other into this Context).

◆ operator[]()

Value::Ref operator[] ( const char * name) const
inline

Access a property of the global object (ctx["fn"](args) is the same as ctx.GlobalObject()["fn"](args)):

ctx["ShowMessage"]("Howdy!"); // `this` = the global object
double score = js::Or(ctx["score"], 0.0);
double total = js::Or(ctx["computeTotal"](3, 4), 0.0);
Parameters
nameThe property name.
Returns
Returns a Value::Ref for the property.

◆ PostTask()

template<typename F>
void PostTask ( F && task) const
inline

Run a function with this context during a later Renderer::Update().

Use this to touch JavaScript from another thread:

ctx.PostTask([](js::Context& live) {
live["progress"] = 0.5;
});
Parameters
taskThe function to run. It can take the live js::Context or nothing.
Note
Safe to call from any thread. Tasks run in the order they were posted.
Note
If the context goes away before the task runs, the task is destroyed without running.

◆ raw()

ULJSContext raw ( ) const
inline

Get the C API handle without transferring ownership.

Returns
Returns the handle.

The documentation for this class was generated from the following file: