docs
Loading...
Searching...
No Matches
ultralight::js

Overview

Type-checked JavaScript bridge between C++ and web pages.

#include <Ultralight/JS.h>

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

The JavaScript API provides two-way communication between your C++ application and the web pages loaded into a View. You can bind functions and properties under a global object that page scripts call like any Web API, or reach into a page to run scripts and call JavaScript functions directly.

Conversions between C++ types and JavaScript values happen automatically. The library checks types at compile time with static assertions and at runtime during every JavaScript call.

Register a bound function on an API attached to a View, then call into the page once the document loads:

js::API game_api("app"); // keep the API alive as long as pages use it
void SetupUI(View* view) {
game_api["add"] = [](double a, double b) { return a + b; }; // app.add(2, 3)
if (game_api.AttachTo(view))
view->LoadURL("file:///app.html");
}
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!"); // calls the page's ShowMessage()
}
Web-page container rendered to an offscreen surface.
Definition View.h:483
virtual void LoadURL(const String &url)=0
Load a URL, the View will navigate to it as a new page.
A global JavaScript namespace for native functions and data.
Definition API.h:398

Where to Start

Common tasks begin with these types:

Task Type
Bind functions and properties js::API
Return Promises from async functions js::Task, js::Resolver
Call page functions or evaluate scripts js::Context
Inspect and convert script values js::Value
Work directly with raw JavaScriptCore View::LockJSContext()

Core Rules

  • Call the API on the Renderer's thread. API::Emit() works from any thread, and copying, moving, or destroying a handle is safe from any thread too.
  • A handle never keeps its page alive. When a page navigates away or its View is destroyed, the handle's page is gone and operations fail safely (see js::Value for the Valid, Empty, and Gone states).
  • The API never throws C++ exceptions. A call that can fail returns a js::Result, which holds either the value or a js::Error.
Note
The bridge requires C++20, and every file that uses the API must use the same C++ exception setting.
Note
DOM elements cross the bridge only with <Ultralight/dom/JSInterop.h>, which this header doesn't include.
See also
js::API, js::Context, js::Value, View::LockJSContext()

Classes

class  API
 A global JavaScript namespace for native functions and data. More...
struct  APIOptions
 Options for creating an API. More...
class  Arg
 An argument passed to a bound function. More...
class  ArrayBuffer
 Handle to a JavaScript ArrayBuffer for sharing raw binary memory with the page. More...
struct  AttachOptions
 Options for API::AttachTo(). More...
class  BindingGuard
 A binding tied to a C++ object's lifetime. More...
class  CallInfo
 Details of a call to a bound function: the context, this, and the raw arguments. More...
class  ClassBuilder
 Builder for exposing a C++ class to JavaScript. More...
struct  ClassHolder
 Type trait that selects the smart pointer type for owned instances of a bound class. More...
class  Context
 JavaScript execution environment for a page. More...
struct  Doc
 A documentation string for a registration (shown in API::schema()). More...
struct  EnumRange
 The range of values searched for an enum's enumerator names. More...
class  Error
 An error from a JavaScript operation. More...
class  Eternal
 Non-owning holder for bound-class singletons and program-lifetime objects. More...
struct  HandleStats
 Counts of the live handles on one context, for finding leaks (see Context::GetHandleStats()). More...
struct  InjectionRequest
 The details an API injection filter decides on (see SetInjectionFilter()). More...
struct  NullType
 Tag type for the JavaScript null value (see js::null). More...
struct  Param
 A parameter name for a registration (shown in API::schema() and in error messages). More...
struct  PendingPromise
 A new pending Promise and the Resolver that settles it (see Context::MakePromise()). More...
class  Resolver
 A handle that settles a JavaScript Promise. More...
class  Task
 A coroutine that returns a JavaScript Promise to the page. More...
class  TypedArray
 Handle to a JavaScript typed array on a page. More...
struct  TypeTraits
 Type conversions between C++ and JavaScript across the bridge. More...
struct  TypeTraits< Color >
 Color as CSS color text. More...
struct  TypeTraits< dom::Element >
 dom::Element as its JavaScript object. More...
struct  TypeTraits< H, std::enable_if_t< detail::kIsCanonicalHolder< H > > >
 Converts a bound class's canonical holder (see js::ClassHolder) with ownership.
struct  TypeTraits< RefPtr< ultralight::Buffer > >
 Marshals RefPtr<Buffer> as a JavaScript ArrayBuffer without copying in either direction. More...
struct  TypeTraits< std::span< T >, std::enable_if_t< detail::kTypedArrayTypeOf< std::remove_const_t< T > > !=kULJSTypedArrayType_None > >
 Marshals a typed-array argument as a std::span<T> without copying.
struct  TypeTraits< String >
 ultralight::String as a JavaScript string in UTF-8, the same as std::string. More...
struct  TypeTraits< T *, std::enable_if_t< std::is_class_v< T > > >
 Converts a pointer to a bound class as a borrowed instance (you keep ownership). More...
struct  TypeTraits< URL >
 URL as its canonical string (see URL::str()). More...
struct  UndefinedType
 Tag type for the JavaScript undefined value (see js::undefined). More...
class  Value
 A handle to a live JavaScript value. More...
class  WeakValue
 A weak reference to a JavaScript object. More...

Concepts

concept  Holder
 Whether or not H (ignoring const and references) is an owning holder: its ultralight::HolderTraits declares element_type, kind, and Get().
concept  LockableHolder
 Whether or not H (ignoring const and references) is a weak holder: its ultralight::HolderTraits declares element_type and a Lock() that returns an owning holder.
concept  Marshalable
 Whether or not js::TypeTraits can convert T (ignoring const, volatile, and references).

Typedefs

using Diagnostics = DiagnosticsLevel
 The diagnostics levels for an API.
template<typename T, typename E = Error>
using Expected = ultralight::detail::Expected<T, E>
 A value of type T or an error of type E (like std::expected).
template<typename T>
using Result = Expected<T, Error>
 The result of a JavaScript operation that can fail: a T or a js::Error.

Enumerations

enum class  AttachFlags : unsigned { None = 0 , AllFrames = 1u << 1 , Mutable = 1u << 2 }
 The flags for API::AttachTo() (the C++ form of ULJSAPIAttachFlags). More...
enum class  ErrorType : unsigned {
  Error = 0 , TypeError , RangeError , SyntaxError ,
  ReferenceError
}
 The type of a JavaScript error, matching the standard error constructors. More...
enum class  PropertyAttributes : unsigned { None = kULJSPropertyAttributes_None , ReadOnly = kULJSPropertyAttributes_ReadOnly , DontEnum = kULJSPropertyAttributes_DontEnum , DontDelete = kULJSPropertyAttributes_DontDelete }
 Attribute flags for a property created by Value::SetProperty(). More...
enum class  Type : unsigned {
  Invalid = kULJSType_Invalid , Undefined = kULJSType_Undefined , Null = kULJSType_Null , Boolean = kULJSType_Boolean ,
  Number = kULJSType_Number , String = kULJSType_String , Symbol = kULJSType_Symbol , BigInt = kULJSType_BigInt ,
  Object = kULJSType_Object
}
 The type of a JavaScript value. More...

Functions

constexpr AttachFlags operator| (AttachFlags a, AttachFlags b)
 Combine attach flags.
constexpr AttachFlags & operator|= (AttachFlags &a, AttachFlags b)
 Add attach flags to a.
template<typename F>
void SetInjectionFilter (View *view, F &&filter)
 Set a View's API filter with a C++ callable (the typed form of View::SetJSAPIInjectionFilter()).
void ClearInjectionFilter (View *view)
 Remove a View's API filter, so the origin rules alone decide which pages get the bindings.
template<typename T, typename M>
requires std::is_member_function_pointer_v<M>
auto Bind (T *instance, M method)
 Bind a member function to an instance without writing a lambda.
template<typename H, typename M>
requires ((Holder<H> || LockableHolder<H>) && std::is_member_function_pointer_v<M>)
auto Bind (H holder, M method)
 Bind a member function to an instance kept by a holder.
template<typename Signature, typename C>
constexpr auto Overload (Signature C::*member)
 Select one overload of a member function for ClassBuilder::Method().
template<typename T>
ClassHolder< std::remove_cv_t< T > >::type Detach (const Value &object)
 Detach a bound-class instance from its wrapper and take ownership back.
template<typename T>
requires std::is_default_constructible_v<T>
T OrEmpty (Result< T > result)
 Get a Result's value, or a default-constructed T if it holds an error.
template<typename T>
 Eternal (T *) -> Eternal< T >
template<typename Fn>
auto RunOnWorker (Fn &&fn)
 Run a function on a background thread, then resume the coroutine on the Renderer's thread with its return value:
template<typename T = Value>
requires Marshalable<T>
auto Await (const Value &promise)
 Wait for a JavaScript promise from a Task:
template<typename T = Value, typename R>
requires (Marshalable<T> && std::is_same_v<std::remove_cvref_t<R>, Result<Value>>)
auto Await (R &&call)
 Call a JavaScript function and wait for the Promise it returns, from a Task:
constexpr PropertyAttributes operator| (PropertyAttributes a, PropertyAttributes b)
 Combine property attribute flags.
bool operator== (const Value &value, NullType)
 Compare against the JavaScript null literal: if (v == js::null).
bool operator== (const Value &value, UndefinedType)
 Compare against the JavaScript undefined literal: if (v == js::undefined).
template<typename T>
T Or (const Value &value, T fallback)
 Convert a value to a C++ type with a fallback (the free-function form of Value::Or()).
std::string Or (const Value &value, const char *fallback)
 Convert a value to a std::string with a string-literal fallback.
template<typename T>
T Or (const Arg &arg, T fallback)
 Convert a callback argument to a C++ type with a fallback.
std::string Or (const Arg &arg, const char *fallback)
 Convert a callback argument to a std::string with a string-literal fallback.
template<typename R, typename T>
requires std::is_same_v<std::remove_cvref_t<R>, Result<Value>>
T Or (const R &result, T fallback)
 Convert the value a call returned to a C++ type with a fallback.
template<typename R>
requires std::is_same_v<std::remove_cvref_t<R>, Result<Value>>
std::string Or (const R &result, const char *fallback)
 Convert the value a call returned to a std::string with a string-literal fallback.
template<typename T, typename U>
requires (!std::is_same_v<T, Value>)
T Or (const Result< T > &result, U &&fallback)
 Get a typed Result's value or fallback if it holds an error.
Value ExceptionValue (const Error &error)
 Get the value a JavaScript exception threw, to keep it or pass it back to the page.

Variables

constexpr AttachFlags AllFrames = AttachFlags::AllFrames
 Shorthand for AttachFlags::AllFrames.
constexpr AttachFlags Mutable = AttachFlags::Mutable
 Shorthand for AttachFlags::Mutable.
constexpr NullType null {}
 The JavaScript null value.
constexpr UndefinedType undefined {}
 The JavaScript undefined value.

Typedef Documentation

◆ Diagnostics

The diagnostics levels for an API.

Diagnostics are development warnings, written to the native logger and to the page's console. Each level does everything the level below it does.

Warn reports mistakes that still run:

  • Typos: reading a missing property of the API's namespace objects logs the closest existing name (myApp.addd is not defined; did you mean add?).
  • Unknown events: subscribing to or emitting an event the API never declared (checked once the API declares at least one event, see DefineEvent()).
  • Lossy numbers: a fractional or out-of-range argument truncated to an integer parameter, or a 64-bit integer return value that a JavaScript number can't hold exactly.
  • Withheld bindings: a page that the origin rules or the View's filter kept the bindings from.
  • Reserved member names: a member named then, toJSON, constructor, or __proto__, which changes how JavaScript treats the object.

Strict also turns two caller mistakes into TypeErrors:

  • A lossy numeric argument (error code ULJS_LOSSY).
  • More arguments than the binding declares (error code ULJS_EXTRA_ARGS). A callable that takes a CallInfo is exempt, since it reads the raw argument list.

A lossy return value still only warns, since the page can't fix a native return type.

Auto (the default) uses the JavaScript level in Config::diagnostics, which is Warn in developer mode and Off otherwise (see DiagnosticsConfig).

Two warnings follow the Config's JavaScript level instead: an operation on a handle whose page is gone, and a JavaScript exception that nothing read. Mistakes found once at registration (an invalid or reserved root path, an invalid binding path, a missing callback) always warn, whatever the level.

Note
Warn and Strict make property reads on the API's namespace objects slower, and attaching the API to a View also attaches the library's ul.diagnostics API.
Note
The UL_JS_DIAGNOSTICS environment variable ("off", "warn", or "strict", any case, read once per process) overrides the level of every API while developer mode is on, so you can switch diagnostics without recompiling.

◆ Expected

template<typename T, typename E = Error>
using Expected = ultralight::detail::Expected<T, E>

A value of type T or an error of type E (like std::expected).

Warning
Don't call value() when has_value() is false. That's undefined behavior, since the library never throws C++ exceptions. Check first or use value_or().

◆ Result

template<typename T>
using Result = Expected<T, Error>

The result of a JavaScript operation that can fail: a T or a js::Error.

Result is js::Expected<T, js::Error>, the library's own type with the members of std::expected (has_value(), value(), error(), value_or(), and_then(), transform(), and the rest). It's the same type in every file of your program, whichever C++ standard each file is compiled with.

Enumeration Type Documentation

◆ AttachFlags

enum class AttachFlags : unsigned
strong

The flags for API::AttachTo() (the C++ form of ULJSAPIAttachFlags).

Enumerator
None 

Main frame only, with frozen namespace objects.

AllFrames 

Also add the bindings to subframes.

Mutable 

Don't freeze the namespace objects (page script can change or replace the bindings).

◆ ErrorType

enum class ErrorType : unsigned
strong

The type of a JavaScript error, matching the standard error constructors.

Enumerator
Error 

A plain Error, or an error type with no dedicated constant.

TypeError 
RangeError 
SyntaxError 
ReferenceError 

◆ PropertyAttributes

enum class PropertyAttributes : unsigned
strong

Attribute flags for a property created by Value::SetProperty().

Combine them with |:

obj.SetProperty("id", ctx.Make(7.0),
@ DontDelete
Script can't delete it.
Definition Value.h:76
@ ReadOnly
Script can't change its value.
Definition Value.h:74
Note
The flags only apply when SetProperty() creates the property. If the object (or its prototype chain) already has one with that name, SetProperty() assigns the value and ignores the flags.
Enumerator
None 

No flags (a normal property).

ReadOnly 

Script can't change its value.

DontEnum 

Hidden from for...in and Object.keys.

DontDelete 

Script can't delete it.

◆ Type

enum class Type : unsigned
strong

The type of a JavaScript value.

Later versions may add types, so handle a value you don't know (eg, with a default case).

See also
Value::type()
Enumerator
Invalid 

An empty Value, or one whose page is gone.

Undefined 
Null 
Boolean 
Number 
String 
Symbol 
BigInt 
Object 

Function Documentation

◆ Await() [1/2]

template<typename T = Value>
requires Marshalable<T>
auto Await ( const Value & promise)

Wait for a JavaScript promise from a Task:

auto Await(const Value &promise)
Wait for a JavaScript promise from a Task:
Definition Task.h:298
Expected< T, Error > Result
The result of a JavaScript operation that can fail: a T or a js::Error.
Definition Error.h:520

The Task resumes on the Renderer's thread during a Renderer::Update() after the promise settles. The Result holds the value converted to T, or an Error: the rejection reason, a TypeError if the value doesn't convert, or a page-gone Error if the page goes away first.

Like JavaScript's await, this also takes a value that isn't a Promise. A value that isn't an object resumes the Task right away with that value. Any other object (eg, a thenable) goes through the page's Promise.resolve() first, which can run page code.

Parameters
promiseThe promise (or other value) to wait for.
Returns
Returns an awaitable that yields a Result<T>.
Note
If promise is empty, the Task resumes right away with an empty-handle Error (or a page-gone Error if its page is gone).
Note
A rejection you wait for this way counts as handled, so the page doesn't report it as unhandled.

◆ Await() [2/2]

template<typename T = Value, typename R>
requires (Marshalable<T> && std::is_same_v<std::remove_cvref_t<R>, Result<Value>>)
auto Await ( R && call)

Call a JavaScript function and wait for the Promise it returns, from a Task:

Result<bool> ok = co_await js::Await<bool>(ask("Overwrite?"));
Result<double> saved = co_await js::Await<double>(game["save"]("slot1"));

This waits for the call's result like the overload above. If the call itself fails (it throws, or the function is empty or its page is gone), the Task resumes right away with that Error.

Parameters
callThe result of the call (a js::Result<js::Value>).
Returns
Returns an awaitable that yields a Result<T>.

◆ Bind() [1/2]

template<typename H, typename M>
requires ((Holder<H> || LockableHolder<H>) && std::is_member_function_pointer_v<M>)
auto Bind ( H holder,
M method )

Bind a member function to an instance kept by a holder.

Any smart pointer with an ultralight::HolderTraits specialization works, built-in or your own:

  • A shared holder (RefPtr, std::shared_ptr, js::Eternal, or your own shared specialization) is kept by the binding, so the instance lives as long as the binding.
  • A weak holder (WeakPtr, std::weak_ptr, or your own specialization with Lock()) is locked for each call and never keeps the instance alive between calls.

A method that returns js::Task<T> keeps the instance alive until its Task finishes, in both forms (the weak form keeps the locked holder), even if the binding is removed meanwhile. A method that takes a trailing js::Resolver binds in both forms too, but the weak form keeps the instance only during the call, not until the Resolver settles.

Parameters
holderThe holder to call the method through (copied into the binding).
methodThe member function pointer.
Returns
Returns a callable that calls method on the held instance.
Note
When the instance is gone (an empty shared holder, or a weak holder whose object was destroyed), a call throws a TypeError with code ULJS_DETACHED into the page instead of touching the missing object. An async binding rejects its Promise with that error.
Note
std::unique_ptr isn't accepted, since passing one would move ownership into the binding. Keep ownership and bind js::Bind(ptr.get(), &T::Method) instead.

◆ Bind() [2/2]

template<typename T, typename M>
requires std::is_member_function_pointer_v<M>
auto Bind ( T * instance,
M method )

Bind a member function to an instance without writing a lambda.

How you pass the instance decides who keeps it alive:

api["save"] = js::Bind(this, &App::OnSave); // raw pointer: you do
api["query"] = js::Bind(database_, &Database::Query); // shared holder: the binding does
api["tick"] = js::Bind(std::weak_ptr(widget_), // weak holder: nobody, and calls
&Widget::OnTick); // fail safely once it's gone
auto Bind(T *instance, M method)
Bind a member function to an instance without writing a lambda.
Definition API.h:1435

The result is an ordinary callable that you can bind anywhere a lambda works. A method that returns js::Task<T> or takes a trailing js::Resolver binds as an async function in every form.

Parameters
instanceThe object to call the method on. It must outlive every call through the binding.
methodThe member function pointer.
Returns
Returns a callable that calls method on instance.

◆ ClearInjectionFilter()

void ClearInjectionFilter ( View * view)
inline

Remove a View's API filter, so the origin rules alone decide which pages get the bindings.

Parameters
viewThe View to clear the filter on (nothing happens if it's nullptr).
Note
Call this on the Renderer's thread.

◆ Detach()

template<typename T>
ClassHolder< std::remove_cv_t< T > >::type Detach ( const Value & object)

Detach a bound-class instance from its wrapper and take ownership back.

After this, calls on the wrapper throw a TypeError with code ULJS_DETACHED instead of reaching the instance. Use it to write close methods (see "Closing an Instance" in js::ClassBuilder), and to detach a borrowed instance's wrapper before you free the instance.

Each page has its own wrapper for an instance, and this detaches only the one you pass. To get an instance's wrapper on a page, convert its pointer there (js::Detach<T>(ctx.Make(ptr))), so before you free a borrowed instance, detach its wrapper on every page you gave it to.

Parameters
objectThe instance's wrapper.
Returns
Returns the instance's canonical holder. Returns an empty holder if the wrapper didn't own the instance (it came from a T*, so the instance is already yours), was already detached, or isn't a wrapper of T. Also returns an empty holder while an async method call on the instance is pending: the wrapper is still detached, and the instance is released after that call's Promise settles (see "Closing an Instance" in js::ClassBuilder).
Note
Call this on the Renderer's thread.

◆ Eternal()

template<typename T>
Eternal ( T * ) -> Eternal< T >

◆ ExceptionValue()

Value ExceptionValue ( const Error & error)
inline

Get the value a JavaScript exception threw, to keep it or pass it back to the page.

js::Result<js::Value> r = ctx.Evaluate("JSON.parse('{')");
if (!r && r.error().is_exception())
ctx["lastError"] = js::ExceptionValue(r.error());
Value ExceptionValue(const Error &error)
Get the value a JavaScript exception threw, to keep it or pass it back to the page.
Definition Value.h:1326
Parameters
errorThe error.
Returns
Returns the thrown value (an empty Value if error doesn't hold a JavaScript exception).

◆ operator==() [1/2]

bool operator== ( const Value & value,
NullType  )
inline

Compare against the JavaScript null literal: if (v == js::null).

Returns
Returns whether the value is JavaScript null.

◆ operator==() [2/2]

bool operator== ( const Value & value,
UndefinedType  )
inline

Compare against the JavaScript undefined literal: if (v == js::undefined).

Returns
Returns whether the value is JavaScript undefined.

◆ operator|() [1/2]

AttachFlags operator| ( AttachFlags a,
AttachFlags b )
constexpr

Combine attach flags.

Returns
Returns the union of both flag sets.

◆ operator|() [2/2]

Combine property attribute flags.

Returns
Returns the union of both flag sets.

◆ operator|=()

AttachFlags & operator|= ( AttachFlags & a,
AttachFlags b )
constexpr

Add attach flags to a.

Returns
Returns a.

◆ Or() [1/7]

std::string Or ( const Arg & arg,
const char * fallback )
inlinenodiscard

Convert a callback argument to a std::string with a string-literal fallback.

Parameters
argThe argument to convert.
fallbackThe text to return if the conversion fails.
Returns
Returns the converted string or fallback on any failure.

◆ Or() [2/7]

template<typename T>
T Or ( const Arg & arg,
T fallback )
nodiscard

Convert a callback argument to a C++ type with a fallback.

Parameters
argThe argument to convert.
fallbackThe value to return if the conversion fails.
Returns
Returns the converted value or fallback on any failure.

◆ Or() [3/7]

template<typename R>
requires std::is_same_v<std::remove_cvref_t<R>, Result<Value>>
std::string Or ( const R & result,
const char * fallback )
nodiscard

Convert the value a call returned to a std::string with a string-literal fallback.

Parameters
resultThe call's result.
fallbackThe text to return if the call or the conversion failed.
Returns
Returns the converted string or fallback on any failure.

◆ Or() [4/7]

template<typename R, typename T>
requires std::is_same_v<std::remove_cvref_t<R>, Result<Value>>
T Or ( const R & result,
T fallback )
nodiscard

Convert the value a call returned to a C++ type with a fallback.

Parameters
resultThe call's result.
fallbackThe value to return if the call or the conversion failed.
Returns
Returns the converted value or fallback on any failure.

◆ Or() [5/7]

template<typename T, typename U>
requires (!std::is_same_v<T, Value>)
T Or ( const Result< T > & result,
U && fallback )
nodiscard

Get a typed Result's value or fallback if it holds an error.

This is the same as result.value_or(fallback) and lets a typed call read like an untyped one: js::Or(fn.Invoke<double>(3, 4), 0.0).

Parameters
resultThe typed result.
fallbackThe value to return if the result holds an error.
Returns
Returns the result's value or fallback.

◆ Or() [6/7]

std::string Or ( const Value & value,
const char * fallback )
inlinenodiscard

Convert a value to a std::string with a string-literal fallback.

Parameters
valueThe value to convert.
fallbackThe text to return if the conversion fails.
Returns
Returns the converted string or fallback on any failure.

◆ Or() [7/7]

template<typename T>
T Or ( const Value & value,
T fallback )
nodiscard

Convert a value to a C++ type with a fallback (the free-function form of Value::Or()).

This takes a Value, a Value::Ref, a js::Arg, or the Result of a call. The value must already have the requested JavaScript type (see Value::To()). Any failure returns fallback (eg, a missing property or a failed call):

double score = js::Or(ctx["score"], 0.0);
double total = js::Or(ctx["computeTotal"](3, 4), 0.0);
std::string name = js::Or(ctx["playerName"](), "guest");
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
Parameters
valueThe value to convert.
fallbackThe value to return if the conversion fails.
Returns
Returns the converted value or fallback on any failure.
Note
Requires <Ultralight/js/TypeTraits.h> (or any header that includes it).

◆ OrEmpty()

template<typename T>
requires std::is_default_constructible_v<T>
T OrEmpty ( Result< T > result)
nodiscard

Get a Result's value, or a default-constructed T if it holds an error.

Use this where an empty value is a fine way to mark failure (every operation on an empty Value fails safely):

js::Value fn = js::OrEmpty(ctx.Evaluate("(x => x * 2)"));
double n = js::OrEmpty(ctx.Evaluate("rawAdd(2, 3)")).Or(0.0);
A handle to a live JavaScript value.
Definition Value.h:210
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
resultThe Result to read.
Returns
Returns the value or a default-constructed T.

◆ Overload()

template<typename Signature, typename C>
auto Overload ( Signature C::* member)
constexpr

Select one overload of a member function for ClassBuilder::Method().

Write the overload's signature as the template argument:

builder.Method("query", js::Overload<Row(const std::string&)>(&Database::Query));
builder.Method("size", js::Overload<size_t() const>(&Database::Size));
constexpr auto Overload(Signature C::*member)
Select one overload of a member function for ClassBuilder::Method().
Definition Class.h:37
Parameters
memberThe overloaded member function.
Returns
Returns the member-function pointer for that overload.

◆ RunOnWorker()

template<typename Fn>
auto RunOnWorker ( Fn && fn)

Run a function on a background thread, then resume the coroutine on the Renderer's thread with its return value:

SaveData data = co_await js::RunOnWorker([&] { return ReadSaveFromDisk(slot); });
auto RunOnWorker(Fn &&fn)
Run a function on a background thread, then resume the coroutine on the Renderer's thread with its re...
Definition Task.h:263

Unlike js::Await() and awaiting a Task, this gives you the function's return value directly (not a Result), so report failures inside that value or, with C++ exceptions enabled, by throwing.

Parameters
fnThe function to run. It takes no arguments.
Returns
Returns an awaitable that yields fn's return value.
Note
The background threads are a small pool shared by the whole library (up to 4 threads, fewer on machines with few cores), so don't block one for a long time.
Note
If the Renderer is destroyed while fn is still waiting for a thread, fn never runs and the coroutine never resumes (its locals are never destroyed). Let pending Tasks finish before you destroy the Renderer.
Note
With C++ exceptions enabled, an exception thrown by fn is rethrown in the coroutine when it resumes, so it rejects the Task's Promise.
Warning
Don't touch JavaScript in fn (js::Value and js::Context only work on the Renderer's thread). Pass plain C++ data in and out.

◆ SetInjectionFilter()

template<typename F>
void SetInjectionFilter ( View * view,
F && filter )

Set a View's API filter with a C++ callable (the typed form of View::SetJSAPIInjectionFilter()).

The View calls the filter each time it's about to add an attached API's bindings to a page: when a page loads, when you attach an API, and when a page returns from the back-forward cache. The origin rules run first and their verdict arrives in rules_allow. Return true to add the bindings or false to withhold them, whatever the rules decided. Use it for decisions that origin rules can't express, such as a user setting or allowing a page whose origin is opaque.

js::SetInjectionFilter(view.get(), [&](const js::InjectionRequest& request) {
if (request.api == debug_api.raw())
return settings.debug_tools_enabled && request.rules_allow;
return request.rules_allow;
});
void SetInjectionFilter(View *view, F &&filter)
Set a View's API filter with a C++ callable (the typed form of View::SetJSAPIInjectionFilter()).
Definition API.h:1386
The details an API injection filter decides on (see SetInjectionFilter()).
Definition API.h:1292
Parameters
viewThe View to set the filter on (nothing happens if it's nullptr).
filterA callable invocable as bool(const js::InjectionRequest&). The new filter replaces (and destroys) the previous one.
Note
Call this on the Renderer's thread. The filter runs there too.
Note
The filter is called for subframes only for APIs attached with AllFrames. The request is valid only during the call.
Note
A filter that throws a C++ exception withholds the API from that page (and the library logs a warning).
See also
ClearInjectionFilter()

Variable Documentation

◆ AllFrames

AttachFlags AllFrames = AttachFlags::AllFrames
inlineconstexpr

Shorthand for AttachFlags::AllFrames.

◆ Mutable

AttachFlags Mutable = AttachFlags::Mutable
inlineconstexpr

Shorthand for AttachFlags::Mutable.

◆ null

NullType null {}
inlineconstexpr

The JavaScript null value.

Use it anywhere a typed value is accepted (eg, obj["x"] = js::null or a bound function's return value).

◆ undefined

UndefinedType undefined {}
inlineconstexpr

The JavaScript undefined value.

Use it the same way as js::null.