docs
Loading...
Searching...
No Matches
Context.h
Go to the documentation of this file.
1///
2/// Copyright (C) 2026 Ultralight, Inc. All rights reserved.
3/// A license is required for commercial use. https://ultralig.ht
4///
5#pragma once
6#include <Ultralight/CAPI/CAPI_JSAPI.h>
7#include <Ultralight/CAPI/CAPI_JSRuntime.h>
8#include <Ultralight/CAPI/CAPI_JSValue.h>
9#include <Ultralight/CAPI/CAPI_String.h>
10#include <Ultralight/View.h>
11#include <Ultralight/detail/Exceptions.h>
12#include <Ultralight/js/API.h>
15#include <Ultralight/js/Error.h>
18#include <Ultralight/js/Value.h>
19
20#include <cstddef>
21#include <initializer_list>
22#include <span>
23#include <string_view>
24#include <type_traits>
25#include <utility>
26#include <vector>
27
28namespace ultralight {
29namespace js {
30
31///
32/// Counts of the live handles on one context, for finding leaks (see Context::GetHandleStats()).
33///
34/// \parblock
35/// @note Copies of one js::Value count once, and the counts include a few handles the library
36/// holds for you (eg, for a Promise made with Context::MakePromise()).
37/// \endparblock
38///
39/// \parblock
40/// @note A destroyed handle can stay counted until the next Renderer::Update().
41/// \endparblock
42///
44 size_t total_values = 0; ///< Live value handles.
45 size_t values_by_type[kULJSType_Count] = {}; ///< Live value handles by js::Type (see count()).
46 size_t weak_refs = 0; ///< Live weak references (0 once the context is gone).
47
48 ///
49 /// Get the number of live value handles of one type.
50 ///
51 /// @param type The value type.
52 ///
53 /// @return Returns the number of live value handles of that type.
54 ///
55 size_t count(Type type) const {
56 size_t index = static_cast<size_t>(type);
57 return index < kULJSType_Count ? values_by_type[index] : 0;
58 }
59
60 ///
61 /// Count the value handles that keep something from being garbage collected (strings,
62 /// symbols, BigInts, and objects).
63 ///
64 /// @return Returns the number of those handles.
65 ///
70};
71
72///
73/// A new pending Promise and the Resolver that settles it (see Context::MakePromise()).
74///
76 Value promise; ///< The Promise to hand to the page.
77 Resolver resolver; ///< Settles `promise` (from any thread).
78};
79
80///
81/// A callback registered with Context::OnDestroyed(), tied to a C++ object's lifetime.
82///
83/// When an armed guard is destroyed before its context goes away, it removes the callback, so
84/// the callback never runs:
85///
86/// ```
87/// class LevelCache {
88/// js::DestroyedGuard guard_;
89///
90/// public:
91/// explicit LevelCache(const js::Context& ctx)
92/// : guard_(ctx.OnDestroyed([this] { Clear(); })) {}
93/// void Clear();
94/// };
95/// ```
96///
97/// To keep the callback for as long as the context lives instead, call Release().
98///
99/// Destroying a guard after its context went away does nothing (the callback already ran).
100///
101/// \parblock
102/// @note Destroying or move-assigning over an armed guard removes the callback, so do it on the
103/// Renderer's thread. To give up a guard on another thread, call Release().
104/// \endparblock
105///
106/// \parblock
107/// @note `operator bool` only says whether the guard is armed. It never reflects whether the
108/// callback ran or the context is still alive.
109/// \endparblock
110///
111class [[nodiscard]] DestroyedGuard {
112 public:
113 ///
114 /// Create an unarmed guard (removes nothing).
115 ///
116 DestroyedGuard() = default;
117
118 ///
119 /// Destructor (removes the callback if the guard is armed).
120 ///
121 ~DestroyedGuard() { Remove(); }
122
123 ///
124 /// Move constructor (`other` becomes unarmed).
125 ///
127 : ctx_(other.ctx_), callback_(other.callback_), user_data_(other.user_data_) {
128 other.Disarm();
129 }
130
131 ///
132 /// Move assignment (removes the current callback first if armed, and `other` becomes unarmed).
133 ///
135 if (this != &other) {
136 Remove();
137 ctx_ = other.ctx_;
138 callback_ = other.callback_;
139 user_data_ = other.user_data_;
140 other.Disarm();
141 }
142 return *this;
143 }
144
147
148 ///
149 /// Disarm the guard without removing the callback (it still runs when the context goes away).
150 ///
151 /// Safe to call from any thread.
152 ///
153 void Release() {
154 ulDestroyJSContext(ctx_);
155 Disarm();
156 }
157
158 ///
159 /// Whether or not the guard is armed (holds a callback to remove).
160 ///
161 explicit operator bool() const { return ctx_ != nullptr; }
162
163 private:
164 friend class Context;
165
166 // Takes ownership of `ctx`, a context reference that keeps the registration's identity
167 // stable. The library owns `user_data` (it frees it through the registration), so the guard
168 // only uses it to match the registration.
169 DestroyedGuard(ULJSContext ctx, ULJSContextDestroyedCallback callback, void* user_data)
170 : ctx_(ctx), callback_(callback), user_data_(user_data) {}
171
172 // Once the context is gone, removal finds nothing and the library has already freed (or
173 // will free) the callable, so this is a no-op then.
174 void Remove() {
175 if (!ctx_)
176 return;
177 ulJSContextRemoveDestroyedCallback(ctx_, callback_, user_data_);
178 Release();
179 }
180
181 void Disarm() {
182 ctx_ = nullptr;
183 callback_ = nullptr;
184 user_data_ = nullptr;
185 }
186
187 ULJSContext ctx_ = nullptr;
188 ULJSContextDestroyedCallback callback_ = nullptr;
189 void* user_data_ = nullptr;
190};
191
192///
193/// JavaScript execution environment for a page.
194///
195/// Every call into a page's JavaScript environment goes through its Context. It represents the
196/// execution state of a loaded document, providing access to the global object where page functions
197/// and variables live.
198///
199/// Construct a Context from a View inside LoadListener::OnDOMReady() to call functions and read
200/// global variables on the page:
201///
202/// ```
203/// void MyApp::OnDOMReady(View* caller, uint64_t frame_id, bool is_main_frame,
204/// const String& url) {
205/// if (!is_main_frame)
206/// return;
207///
208/// js::Context ctx(caller);
209/// ctx["ShowMessage"]("Howdy!"); // call a page function
210/// double score = js::Or(ctx["score"], 0.0); // read a global (0.0 if it fails)
211/// double doubled = js::Or(ctx.Evaluate<double>("score * 2"), 0.0);
212/// }
213/// ```
214///
215/// ## Getting a Context
216///
217/// Constructing a Context with a View wraps the main frame's JavaScript environment. To access the
218/// Context of a subframe or a specific document, pass that document to dom::GetJSContext().
219///
220/// You'll typically construct a Context inside a LoadListener callback:
221///
222/// - **Use LoadListener::OnDOMReady() for work that needs the document or its scripts.** It fires
223/// once the DOM is fully parsed and page scripts have run.
224/// - **Use LoadListener::OnWindowObjectReady() to set up global state early.** It fires before the
225/// page's own scripts run.
226///
227/// Each page gets its own Context. When a View navigates to a new page, the old Context's page is
228/// gone, along with every Value created from it (see js::Value for what that means), so you'll need
229/// to obtain a new Context for the new page. Operations on a Context whose page is gone fail safely
230/// instead of crashing.
231///
232/// ## Creating Values
233///
234/// Call Make() to convert a native C++ value into a JavaScript Value. The method converts any type
235/// that js::TypeTraits supports, including numbers, strings, standard containers, reflected
236/// structs, and enums.
237///
238/// Convert a reflected struct to a JavaScript object and pass it to a page function:
239///
240/// ```
241/// struct HudSettings {
242/// std::string theme;
243/// double volume;
244/// };
245///
246/// js::Value settings = ctx.Make(HudSettings { "dark", 0.8 });
247/// ctx["applySettings"](settings);
248/// ```
249///
250/// \parblock
251/// @note Context operations must run on the Renderer's thread. To dispatch work from another
252/// thread, call PostTask() to schedule a callback that runs during a later
253/// Renderer::Update().
254/// \endparblock
255///
256/// \parblock
257/// @note js::Context and dom::data::Context are unrelated types (dom::data::Context manages
258/// declarative data bindings).
259/// \endparblock
260///
261/// @see js::Value, js::CallInfo::context(), dom::GetJSContext(), LoadListener::OnDOMReady()
262///
263class Context {
264 public:
265 ///
266 /// Create an empty Context.
267 ///
268 Context() = default;
269
270 ///
271 /// Get the context of a View's main frame.
272 ///
273 /// @param view The View. The Context is empty if `view` is NULL or its page can't run script
274 /// (JavaScript is disabled or the document is sandboxed).
275 ///
276 /// @note A Context belongs to the page loaded now. After the View loads a new page, get a new
277 /// Context.
278 ///
279 explicit Context(View* view) : handle_(view ? view->GetJSContext() : nullptr) {}
280
281 ///
282 /// Get the context a value belongs to.
283 ///
284 /// @param value The value. An empty Value gives an empty Context, and a Value whose page is
285 /// gone gives a Context whose page is also gone.
286 ///
287 explicit Context(const Value& value)
288 : handle_(value.raw() ? ulJSValueGetContext(value.raw()) : nullptr) {}
289
290 // --- Interop with the C API (most embedders never touch raw handles) -------------------
291
292 ///
293 /// Take ownership of a context handle from the C API.
294 ///
295 /// @param handle The handle to take ownership of.
296 ///
297 /// @return Returns a Context that owns `handle`.
298 ///
299 /// @warning Don't pass a handle the library owns (eg, one a callback receives). Use
300 /// FromBorrowed() for that.
301 ///
302 static Context Adopt(ULJSContext handle) { return Context(handle); }
303
304 ///
305 /// Add a reference to a context handle the library owns (eg, the context a C API callback
306 /// receives) so you can use it with this class and keep it after the callback.
307 ///
308 /// @param handle The borrowed handle.
309 ///
310 /// @return Returns a Context with its own reference to `handle`.
311 ///
313 return Context(handle ? ulCreateJSContextRef(handle) : nullptr);
314 }
315
316 ///
317 /// Copy constructor (refers to the same context).
318 ///
319 Context(const Context& other)
320 : handle_(other.handle_ ? ulCreateJSContextRef(other.handle_) : nullptr) {}
321
322 ///
323 /// Move constructor (`other` becomes empty).
324 ///
325 Context(Context&& other) noexcept : handle_(other.handle_) { other.handle_ = nullptr; }
326
327 ///
328 /// Assignment (copies or moves `other` into this Context).
329 ///
330 Context& operator=(Context other) noexcept {
331 std::swap(handle_, other.handle_);
332 return *this;
333 }
334
335 ///
336 /// Destructor (releases this handle).
337 ///
338 ~Context() { ulDestroyJSContext(handle_); }
339
340 ///
341 /// Whether or not this Context is valid (it isn't empty and its page is still alive).
342 ///
343 explicit operator bool() const { return handle_ && ulJSContextIsAlive(handle_); }
344
345 ///
346 /// Whether or not this Context holds nothing.
347 ///
348 bool IsEmpty() const { return handle_ == nullptr; }
349
350 ///
351 /// Whether or not this Context's page is still alive (the same test as `operator bool`).
352 ///
353 /// @note Safe to call from any thread, but off the Renderer's thread the result may already
354 /// be out of date when you act on it.
355 ///
356 bool IsAlive() const { return handle_ && ulJSContextIsAlive(handle_); }
357
358 ///
359 /// Run a script and get its completion value.
360 ///
361 /// @param script The script (UTF-8; embedded null characters are kept).
362 ///
363 /// @param source_url A URL for the script, used in error reports (may be NULL).
364 ///
365 /// @return Returns the script's completion value. Fails with a JavaScript exception if the
366 /// script throws.
367 ///
368 [[nodiscard]] Result<Value> Evaluate(std::string_view script,
369 const char* source_url = nullptr) const {
370 if (!handle_)
371 return detail::EmptyHandleError();
372 ULString source = ulCreateStringUTF8(script.data(), script.size());
373 ULJSValue exception = nullptr;
374 ULJSValue result = ulJSContextEvaluate(handle_, source, source_url, &exception);
375 ulDestroyString(source);
376 if (!result) {
377 if (exception)
378 return Unexpected<Error>(Error::AdoptException(exception));
379 return Unexpected<Error>(Error::PageGone());
380 }
381 return Value::Adopt(result);
382 }
383
384 ///
385 /// Run a script and convert its completion value to a C++ type (see Value::To()).
386 ///
387 /// ```
388 /// js::Result<double> health = ctx.Evaluate<double>("game.player.health");
389 /// double speed = ctx.Evaluate<double>("game.player.speed").value_or(1.0);
390 /// ```
391 ///
392 /// @param script The script (UTF-8; embedded null characters are kept).
393 ///
394 /// @param source_url A URL for the script, used in error reports (may be NULL).
395 ///
396 /// @return Returns the converted value. Fails with a JavaScript exception if the script
397 /// throws, or with a TypeError if the value doesn't convert to T.
398 ///
399 template <typename T>
400 requires Marshalable<T>
401 [[nodiscard]] Result<T> Evaluate(std::string_view script,
402 const char* source_url = nullptr) const {
403 Result<Value> completion = Evaluate(script, source_url);
404 if (!completion)
405 return Unexpected<Error>(std::move(completion).error());
406 return completion.value().To<T>();
407 }
408
409 ///
410 /// Get the global object.
411 ///
412 /// @return Returns the global object (an empty Value if the context is gone).
413 ///
415 return Value::Adopt(ulJSContextGetGlobalObject(handle_));
416 }
417
418 ///
419 /// Access a property of the global object (`ctx["fn"](args)` is the same as
420 /// `ctx.GlobalObject()["fn"](args)`):
421 ///
422 /// ```
423 /// ctx["ShowMessage"]("Howdy!"); // `this` = the global object
424 /// double score = js::Or(ctx["score"], 0.0);
425 /// double total = js::Or(ctx["computeTotal"](3, 4), 0.0);
426 /// ```
427 ///
428 /// @param name The property name.
429 ///
430 /// @return Returns a Value::Ref for the property.
431 ///
432 Value::Ref operator[](const char* name) const {
433 Value global = GlobalObject();
434 Value::Ref ref = global[name];
435 // The global object reads empty only when the context's page is gone.
436 ref.source_gone_ = handle_ && global.IsEmpty();
437 return ref;
438 }
439
440 ///
441 /// Convert a C++ value to a JavaScript value through js::TypeTraits.
442 ///
443 /// This works for every supported type, including reflected structs, enums, containers,
444 /// js::null, and js::undefined.
445 ///
446 /// @param value The C++ value to convert.
447 ///
448 /// @return Returns the new value (an empty Value if the context is gone).
449 ///
450 template <typename T>
451 Value Make(T&& value) const {
452 using U = std::decay_t<T>;
453 detail::AssertInteropHeader<U>();
454 static_assert(Marshalable<U>,
455 "no js::TypeTraits for T: use a supported built-in, make it a plain "
456 "aggregate struct, or specialize js::TypeTraits for it");
457 return Value::Adopt(handle_ ? TypeTraits<U>::ToJS(handle_, value) : nullptr);
458 }
459
460 ///
461 /// Create a new empty JavaScript object.
462 ///
463 /// @return Returns the new object (an empty Value if the context is gone).
464 ///
465 Value MakeObject() const { return Value::Adopt(ulCreateJSObject(handle_)); }
466
467 ///
468 /// Create a new JavaScript Array.
469 ///
470 /// @param elements The elements (an empty Value becomes `undefined`).
471 ///
472 /// @param count The number of entries in `elements`.
473 ///
474 /// @return Returns the new Array (an empty Value if the context or an element's page is gone).
475 ///
476 Value MakeArray(const Value* elements, size_t count) const {
477 if (!handle_)
478 return Value();
479 std::vector<ULJSValue> raw(count);
480 for (size_t i = 0; i < count; i++)
481 raw[i] = elements[i].raw();
482 return Value::Adopt(ulCreateJSArray(handle_, count ? raw.data() : nullptr, count));
483 }
484
485 ///
486 /// Create a new JavaScript Array from a brace list (eg, `ctx.MakeArray({ a, b })`).
487 ///
488 /// @param elements The elements.
489 ///
490 /// @return Returns the new Array (an empty Value if the context or an element's page is gone).
491 ///
492 Value MakeArray(std::initializer_list<Value> elements) const {
493 return MakeArray(elements.begin(), elements.size());
494 }
495
496 ///
497 /// Create a new JavaScript Array from a range (eg, a `std::vector<js::Value>`).
498 ///
499 /// @param elements The elements.
500 ///
501 /// @return Returns the new Array (an empty Value if the context or an element's page is gone).
502 ///
503 Value MakeArray(std::span<const Value> elements) const {
504 return MakeArray(elements.data(), elements.size());
505 }
506
507 ///
508 /// Create a value from JSON text (the reverse of Value::ToJSON()):
509 ///
510 /// ```
511 /// js::Value config = js::OrEmpty(ctx.MakeFromJSON(R"({"volume": 5, "muted": false})"));
512 /// ```
513 ///
514 /// @param json The JSON text (any JSON value).
515 ///
516 /// @return Returns the new value. Fails with a SyntaxError (a JavaScript exception) if the
517 /// JSON is invalid.
518 ///
519 [[nodiscard]] Result<Value> MakeFromJSON(std::string_view json) const {
520 if (!handle_)
521 return detail::EmptyHandleError();
522 ULString text = ulCreateStringUTF8(json.data(), json.length());
523 ULJSValue exception = nullptr;
524 ULJSValue result = ulCreateJSValueFromJSON(handle_, text, &exception);
525 ulDestroyString(text);
526 if (!result) {
527 if (exception)
528 return Unexpected<Error>(Error::AdoptException(exception));
529 return Unexpected<Error>(Error::PageGone());
530 }
531 return Value::Adopt(result);
532 }
533
534 ///
535 /// Run a function with this context during a later Renderer::Update().
536 ///
537 /// Use this to touch JavaScript from another thread:
538 ///
539 /// ```
540 /// ctx.PostTask([](js::Context& live) {
541 /// live["progress"] = 0.5;
542 /// });
543 /// ```
544 ///
545 /// @param task The function to run. It can take the live js::Context or nothing.
546 ///
547 /// \parblock
548 /// @note Safe to call from any thread. Tasks run in the order they were posted.
549 /// \endparblock
550 ///
551 /// \parblock
552 /// @note If the context goes away before the task runs, the task is destroyed without running.
553 /// \endparblock
554 ///
555 template <typename F>
556 void PostTask(F&& task) const {
557 using Fn = std::decay_t<F>;
558 static_assert(std::is_invocable_v<Fn&> || std::is_invocable_v<Fn&, Context&>,
559 "js::Context::PostTask takes a callable invocable with nothing or with "
560 "js::Context&");
561 ulJSContextPostTask(handle_, &TaskThunk<Fn>, new Fn(std::forward<F>(task)),
562 &DeleteCallable<Fn>);
563 }
564
565 ///
566 /// Create a pending Promise and the Resolver that settles it, to hand a Promise to the page
567 /// outside a bound function:
568 ///
569 /// ```
570 /// auto [promise, resolver] = ctx.MakePromise();
571 /// ctx["ready"] = promise;
572 /// // later, from any thread:
573 /// resolver.Resolve(std::string("ok"));
574 /// ```
575 ///
576 /// @return Returns the Promise and its Resolver (both empty if the context is gone).
577 ///
579 ULJSPromiseResolver raw = nullptr;
580 ULJSValue promise = handle_ ? ulCreateJSPromise(handle_, &raw) : nullptr;
581 if (!promise)
582 return {};
583 return PendingPromise { Value::Adopt(promise), Resolver::Adopt(raw) };
584 }
585
586 ///
587 /// Create an ArrayBuffer that shares a Buffer's bytes with JavaScript without copying.
588 ///
589 /// The ArrayBuffer keeps a reference to `buffer` until it's garbage collected or detached
590 /// (see "Byte Lifetimes" on js::ArrayBuffer).
591 ///
592 /// @param buffer The buffer to share. An empty buffer gives an ordinary empty ArrayBuffer
593 /// that keeps no reference.
594 ///
595 /// @return Returns a new ArrayBuffer over the buffer's bytes (an empty wrapper if `buffer`
596 /// is null or the context is gone).
597 ///
599 if (!handle_)
600 return ArrayBuffer();
601 return ArrayBuffer(
602 Value::Adopt(detail::WrapBufferThrough(handle_, buffer, [&](ULBuffer shared) {
603 return ulCreateJSArrayBufferFromBuffer(handle_, shared);
604 })));
605 }
606
607 ///
608 /// Create an ArrayBuffer holding a copy of the given bytes.
609 ///
610 /// @param bytes The bytes to copy (may be NULL only when `length` is 0).
611 ///
612 /// @param length The number of bytes to copy (0 creates an empty ArrayBuffer).
613 ///
614 /// @return Returns a new ArrayBuffer (an empty wrapper if `bytes` is NULL and `length`
615 /// isn't 0, or if the context is gone).
616 ///
617 ArrayBuffer MakeArrayBuffer(const void* bytes, size_t length) const {
618 return ArrayBuffer(Value::Adopt(ulCreateJSArrayBuffer(handle_, bytes, length)));
619 }
620
621 ///
622 /// Create a typed array of zero-filled elements of type `T` (eg, `MakeTypedArray<float>(4)`
623 /// creates a Float32Array; see js::TypedArray for the element types).
624 ///
625 /// @param length The number of elements (not bytes).
626 ///
627 /// @return Returns a new TypedArray (an empty wrapper if the context is gone).
628 ///
629 template <typename T>
630 TypedArray<T> MakeTypedArray(size_t length) const {
631 return TypedArray<T>(
632 Value::Adopt(ulCreateJSTypedArray(handle_, detail::kTypedArrayTypeOf<T>, length)));
633 }
634
635 ///
636 /// Create a typed array of elements of type `T` that shares a Buffer's bytes with JavaScript
637 /// without copying.
638 ///
639 /// Lifetime works as for MakeArrayBuffer().
640 ///
641 /// @param buffer The buffer to share (its size must be a multiple of `sizeof(T)`). An empty
642 /// buffer gives an ordinary empty typed array that keeps no reference.
643 ///
644 /// @return Returns a new TypedArray over the buffer's bytes (an empty wrapper if `buffer`
645 /// is null, its size isn't a multiple of `sizeof(T)`, or the context is gone).
646 ///
647 template <typename T>
649 if (!handle_)
650 return TypedArray<T>();
651 return TypedArray<T>(
652 Value::Adopt(detail::WrapBufferThrough(handle_, buffer, [&](ULBuffer shared) {
653 return ulCreateJSTypedArrayFromBuffer(handle_, detail::kTypedArrayTypeOf<T>, shared);
654 })));
655 }
656
657 ///
658 /// Create a JavaScript function backed by a C++ callable, to hand to the page (eg, as a
659 /// callback). Arguments convert the same way as for a js::API binding:
660 ///
661 /// ```
662 /// js::Value cb = ctx.MakeFunction("onTick", [](double dt) { ... });
663 /// ```
664 ///
665 /// @param name The function's `name`, also used in its conversion errors.
666 ///
667 /// @param fn The callable.
668 ///
669 /// @return Returns the function (an empty Value if the context is gone).
670 ///
671 /// \parblock
672 /// @note Only synchronous callables work here (returning a value or a js::Result). Bind async
673 /// functions (a js::Task or a trailing js::Resolver) through js::API.
674 /// \endparblock
675 ///
676 /// \parblock
677 /// @note The callable is destroyed on the Renderer's thread after the function is garbage
678 /// collected.
679 /// \endparblock
680 ///
681 template <typename Fn>
682 Value MakeFunction(const char* name, Fn&& fn) const {
683 using F = std::decay_t<Fn>;
684 using Traits = detail::CallableTraits<F>;
685 using Shape = detail::ParamShape<typename Traits::Params>;
686 static_assert(!Shape::kHasResolver
687 && !detail::kIsAsyncReturn<typename Traits::Return>,
688 "MakeFunction binds synchronous callables; bind async forms (js::Task, "
689 "trailing js::Resolver) through js::API");
690 [&]<size_t... Is>(std::index_sequence<Is...>) {
691 (detail::ValidateParam<std::tuple_element_t<Is, typename Shape::Converted>>(), ...);
692 }(std::make_index_sequence<Shape::kCount> {});
693 if (!handle_)
694 return Value();
695 auto* bound = new detail::BoundCallable<F> { std::forward<Fn>(fn),
696 std::string(name ? name : ""), {}, {} };
697 return Value::Adopt(ulCreateJSFunction(handle_, name, &detail::SyncTrampoline<F>, bound,
698 &detail::DestroyBoundCallable<F>));
699 }
700
701 ///
702 /// Create a JavaScript Date (like `new Date(ms_since_epoch)`).
703 ///
704 /// ```
705 /// ctx["lastSave"] = ctx.MakeDate(1767225600000.0); // 2026-01-01T00:00:00Z
706 /// ```
707 ///
708 /// @param ms_since_epoch The time value, in milliseconds since the epoch (1970-01-01 UTC).
709 /// A fraction is truncated. NaN, an infinity, or a value further than
710 /// 8.64e15 from the epoch gives an Invalid Date.
711 ///
712 /// @return Returns the new Date (an empty Value if the context is gone).
713 ///
714 /// @see Value::TimeValue()
715 ///
716 Value MakeDate(double ms_since_epoch) const {
717 return Value::Adopt(handle_ ? ulCreateJSDate(handle_, ms_since_epoch) : nullptr);
718 }
719
720 ///
721 /// Run a function when this context goes away, to clear anything you keep per page.
722 ///
723 /// The function runs once on the Renderer's thread, right when the context goes away: its page
724 /// navigates away (including into the back-forward cache), its frame is removed, or its View
725 /// or the Renderer is destroyed.
726 ///
727 /// ```
728 /// js::DestroyedGuard guard = ctx.OnDestroyed([] { g_player_cache.clear(); });
729 /// guard.Release(); // keep it for the rest of the context's life
730 /// ```
731 ///
732 /// @param fn The function to run. It can take the js::Context that went away or nothing.
733 ///
734 /// @return Returns a guard that removes the function when destroyed (see js::DestroyedGuard).
735 /// The guard is unarmed if this Context is empty or its page is already gone, and
736 /// then `fn` never runs.
737 ///
738 /// \parblock
739 /// @note The context is already gone when `fn` runs, so use it to clear caches and destroy
740 /// handles, not to run script.
741 /// \endparblock
742 ///
743 /// \parblock
744 /// @note A page restored from the back-forward cache gets a new Context, so `fn` running
745 /// means this context is over, not that the page is gone for good.
746 /// \endparblock
747 ///
748 template <typename F>
750 using Fn = std::decay_t<F>;
751 static_assert(std::is_invocable_v<Fn&> || std::is_invocable_v<Fn&, Context&>,
752 "js::Context::OnDestroyed takes a callable invocable with nothing or with "
753 "js::Context&");
754 if (!handle_ || !ulJSContextIsAlive(handle_))
755 return DestroyedGuard();
756 auto* callable = new Fn(std::forward<F>(fn));
757 // The library owns `callable` from here: it runs DeleteCallable after the callback runs or
758 // once the registration is removed.
759 ulJSContextAddDestroyedCallback(handle_, &DestroyedThunk<Fn>, callable,
760 &DeleteCallable<Fn>);
761 return DestroyedGuard(ulCreateJSContextRef(handle_), &DestroyedThunk<Fn>, callable);
762 }
763
764 ///
765 /// Count the live handles on this context, for finding leaks.
766 ///
767 /// Value handles you never destroy keep counting after the page goes away.
768 ///
769 /// @return Returns the counts (all zero for an empty Context).
770 ///
771 /// @see HandleStats
772 ///
774 HandleStats stats = {};
775 ULJSHandleStats raw_stats = {};
776 if (handle_ && ulJSContextGetHandleStats(handle_, &raw_stats)) {
777 stats.total_values = raw_stats.total_values;
778 for (size_t i = 0; i < kULJSType_Count; i++)
779 stats.values_by_type[i] = raw_stats.values_by_type[i];
780 stats.weak_refs = raw_stats.weak_refs;
781 }
782 return stats;
783 }
784
785 ///
786 /// Get the C API handle without transferring ownership.
787 ///
788 /// @return Returns the handle.
789 ///
790 ULJSContext raw() const { return handle_; }
791
792 ///
793 /// Give up ownership of the C API handle and return it.
794 ///
795 /// @return Returns the handle. You must call ulDestroyJSContext() when finished.
796 ///
798 ULJSContext handle = handle_;
799 handle_ = nullptr;
800 return handle;
801 }
802
803 private:
804 explicit Context(ULJSContext handle) : handle_(handle) {}
805
806 // Runs a nullary or Context& callable for a library callback. It runs inside the library's
807 // update or teardown, so an exception must not unwind into it.
808 template <typename Fn>
809 static void InvokeWithContext(void* user_data, ULJSContext ctx, const char* where) {
810 Fn& fn = *static_cast<Fn*>(user_data);
811 ultralight::detail::CallCatchingExceptions(
812 [&] {
813 if constexpr (std::is_invocable_v<Fn&, Context&>) {
814 Context borrowed = Context::FromBorrowed(ctx);
815 fn(borrowed);
816 } else {
817 fn();
818 }
819 },
820 [where](const char* what) { detail::LogNativeException(where, what); });
821 }
822
823 template <typename Fn>
824 static void TaskThunk(void* user_data, ULJSContext ctx) {
825 InvokeWithContext<Fn>(user_data, ctx, "js::Context::PostTask");
826 }
827
828 template <typename Fn>
829 static void DestroyedThunk(void* user_data, ULJSContext ctx) {
830 InvokeWithContext<Fn>(user_data, ctx, "js::Context::OnDestroyed");
831 }
832
833 template <typename Fn>
834 static void DeleteCallable(void* user_data) {
835 delete static_cast<Fn*>(user_data);
836 }
837
838 ULJSContext handle_ = nullptr;
839};
840
842 return Context::FromBorrowed(ctx_);
843}
844
845} // namespace js
846} // namespace ultralight
struct C_JSContext * ULJSContext
Opaque handle to a JavaScript execution context (one page's script world in one View).
Definition View.h:25
A nullable smart pointer.
Definition RefPtr.h:126
Web-page container rendered to an offscreen surface.
Definition View.h:483
Handle to a JavaScript ArrayBuffer for sharing raw binary memory with the page.
Definition Buffer.h:88
ArrayBuffer()=default
Create an empty ArrayBuffer wrapper.
Context context() const
Get the calling context, to create values in it or to keep it after the call:
Definition Context.h:841
JavaScript execution environment for a page.
Definition Context.h:263
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)...
Definition Context.h:432
Value MakeArray(std::span< const Value > elements) const
Create a new JavaScript Array from a range (eg, a std::vector<js::Value>).
Definition Context.h:503
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 copyi...
Definition Context.h:648
Value Make(T &&value) const
Convert a C++ value to a JavaScript value through js::TypeTraits.
Definition Context.h:451
Value GlobalObject() const
Get the global object.
Definition Context.h:414
ArrayBuffer MakeArrayBuffer(const RefPtr< ultralight::Buffer > &buffer) const
Create an ArrayBuffer that shares a Buffer's bytes with JavaScript without copying.
Definition Context.h:598
Value MakeArray(const Value *elements, size_t count) const
Create a new JavaScript Array.
Definition Context.h:476
Result< Value > Evaluate(std::string_view script, const char *source_url=nullptr) const
Run a script and get its completion value.
Definition Context.h:368
Value MakeArray(std::initializer_list< Value > elements) const
Create a new JavaScript Array from a brace list (eg, ctx.MakeArray({ a, b })).
Definition Context.h:492
Context(const Context &other)
Copy constructor (refers to the same context).
Definition Context.h:319
ULJSContext raw() const
Get the C API handle without transferring ownership.
Definition Context.h:790
Context()=default
Create an empty Context.
Context & operator=(Context other) noexcept
Assignment (copies or moves other into this Context).
Definition Context.h:330
Context(Context &&other) noexcept
Move constructor (other becomes empty).
Definition Context.h:325
static Context Adopt(ULJSContext handle)
Take ownership of a context handle from the C API.
Definition Context.h:302
bool IsEmpty() const
Whether or not this Context holds nothing.
Definition Context.h:348
bool IsAlive() const
Whether or not this Context's page is still alive (the same test as operator bool).
Definition Context.h:356
HandleStats GetHandleStats() const
Count the live handles on this context, for finding leaks.
Definition Context.h:773
Value MakeObject() const
Create a new empty JavaScript object.
Definition Context.h:465
PendingPromise MakePromise() const
Create a pending Promise and the Resolver that settles it, to hand a Promise to the page outside a bo...
Definition Context.h:578
Context(View *view)
Get the context of a View's main frame.
Definition Context.h:279
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).
Definition Context.h:682
Context(const Value &value)
Get the context a value belongs to.
Definition Context.h:287
Value MakeDate(double ms_since_epoch) const
Create a JavaScript Date (like new Date(ms_since_epoch)).
Definition Context.h:716
~Context()
Destructor (releases this handle).
Definition Context.h:338
void PostTask(F &&task) const
Run a function with this context during a later Renderer::Update().
Definition Context.h:556
DestroyedGuard OnDestroyed(F &&fn) const
Run a function when this context goes away, to clear anything you keep per page.
Definition Context.h:749
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()).
Definition Context.h:401
Result< Value > MakeFromJSON(std::string_view json) const
Create a value from JSON text (the reverse of Value::ToJSON()):
Definition Context.h:519
static Context FromBorrowed(ULJSContext handle)
Add a reference to a context handle the library owns (eg, the context a C API callback receives) so y...
Definition Context.h:312
ArrayBuffer MakeArrayBuffer(const void *bytes, size_t length) const
Create an ArrayBuffer holding a copy of the given bytes.
Definition Context.h:617
ULJSContext LeakRef()
Give up ownership of the C API handle and return it.
Definition Context.h:797
TypedArray< T > MakeTypedArray(size_t length) const
Create a typed array of zero-filled elements of type T (eg, MakeTypedArray<float>(4) creates a Float3...
Definition Context.h:630
A callback registered with Context::OnDestroyed(), tied to a C++ object's lifetime.
Definition Context.h:111
DestroyedGuard(DestroyedGuard &&other) noexcept
Move constructor (other becomes unarmed).
Definition Context.h:126
DestroyedGuard & operator=(DestroyedGuard &&other) noexcept
Move assignment (removes the current callback first if armed, and other becomes unarmed).
Definition Context.h:134
void Release()
Disarm the guard without removing the callback (it still runs when the context goes away).
Definition Context.h:153
DestroyedGuard(const DestroyedGuard &)=delete
friend class Context
Definition Context.h:164
~DestroyedGuard()
Destructor (removes the callback if the guard is armed).
Definition Context.h:121
DestroyedGuard & operator=(const DestroyedGuard &)=delete
DestroyedGuard()=default
Create an unarmed guard (removes nothing).
static Error AdoptException(ULJSValue exception)
Create an error from a JavaScript exception, taking ownership of the handle.
Definition Error.h:131
static Error PageGone()
Create a page-gone error (is_page_gone() returns true).
Definition Error.h:122
A handle that settles a JavaScript Promise.
Definition Resolver.h:97
static Resolver Adopt(ULJSPromiseResolver handle)
Take ownership of a resolver handle from the C API.
Definition Resolver.h:120
Handle to a JavaScript typed array on a page.
Definition Buffer.h:203
TypedArray()=default
Create an empty TypedArray wrapper.
A reference to a property of a Value (returned by Value::operator[]).
Definition Value.h:1419
A handle to a live JavaScript value.
Definition Value.h:276
static Value Adopt(ULJSValue handle)
Take ownership of a handle from the C API without adding a reference.
Definition Value.h:1242
bool IsEmpty() const
Whether or not this Value holds nothing (see "Handle States" above).
Definition Value.h:315
Value()
Create an empty Value.
Definition Value.h:281
Whether or not js::TypeTraits can convert T (ignoring const, volatile, and references).
Definition TypeTraits.h:279
Type-checked JavaScript bridge between C++ and web pages.
Definition JSInterop.h:141
Type
The type of a JavaScript value.
Definition Value.h:97
@ Symbol
Definition Value.h:104
@ String
Definition Value.h:103
@ Object
Definition Value.h:106
@ BigInt
Definition Value.h:105
Expected< T, Error > Result
The result of a JavaScript operation that can fail: a T or a js::Error.
Definition Error.h:520
Root namespace for every public Ultralight type, function, and enumeration.
Counts of the live handles on one context, for finding leaks (see Context::GetHandleStats()).
Definition Context.h:43
size_t weak_refs
Live weak references (0 once the context is gone).
Definition Context.h:46
size_t count(Type type) const
Get the number of live value handles of one type.
Definition Context.h:55
size_t ProtectedEstimate() const
Count the value handles that keep something from being garbage collected (strings,...
Definition Context.h:66
size_t total_values
Live value handles.
Definition Context.h:44
size_t values_by_type[kULJSType_Count]
Live value handles by js::Type (see count()).
Definition Context.h:45
A new pending Promise and the Resolver that settles it (see Context::MakePromise()).
Definition Context.h:75
Value promise
The Promise to hand to the page.
Definition Context.h:76
Resolver resolver
Settles promise (from any thread).
Definition Context.h:77
Type conversions between C++ and JavaScript across the bridge.
Definition TypeTraits.h:244