docs
Loading...
Searching...
No Matches
Triggers

#include <Ultralight/dom/Triggers.h>

Overview

A set of DOM event listeners and lifecycle hooks that persists across page navigations.

You define DOM event listeners and setup hooks in a dom::Triggers set and attach it to a View instead of re-registering handlers on every page load. One set can serve several Views, and it functions even when JavaScript is disabled.

Attach the set to a View before loading content so every page gets the listeners:

ui.On("#save", "click", [] { SaveGame(); });
ui.OnDOMReady([](dom::Document document) {
document.getElementById("status").textContent = "Ready";
});
if (ui.AttachTo(view.get()))
view->LoadURL("file:///app.html");
The root of a page's DOM tree in a View or frame.
Definition Document.h:106
Element getElementById(std::string_view id) const
Find the element with a certain id (getElementById).
Definition Document.h:190
detail::StringProp< detail::TextContentTag > textContent
The text of this element and all its descendants (textContent).
Definition Element.h:216
A set of DOM event listeners and lifecycle hooks that persists across page navigations.
Definition Triggers.h:253
bool AttachTo(View *view, const AttachOptions &options={})
Attach this set to a View.
Definition Triggers.h:472
void OnDOMReady(F &&callback)
Add a hook that runs on each page that gets the set, once its document has finished parsing.
Definition Triggers.h:421
bool On(std::string_view selector, std::string_view type, F &&callback, EventListenerFlags flags=EventListenerFlags::None)
Add a listener for events on elements matching a CSS selector.
Definition Triggers.h:338

Delivery Timing

Pages receive an attached set based on their load state:

  • A loading page gets the set once its document finishes parsing. Any OnDOMReady() hooks run right after the listeners attach.
  • Attaching after a page has loaded applies the listeners right away. Any OnDOMReady() hooks run synchronously inside AttachTo().
  • Handlers added after attaching reach only subsequent pages. The current page keeps its existing listeners unchanged.
Note
The page's own DOMContentLoaded event fires before the set arrives. Use OnDOMReady() for setup code that runs once document parsing completes.

Origin Rules and Page Filtering

By default, only your own content gets the set (file:// pages and View::LoadHTML()). Passing custom origin rules in AttachOptions replaces this default policy:

  • Local pages require an explicit "file://*" rule. Without it, local content stops receiving the set.
  • Pages loaded without a URL match no origin rule. Content loaded through View::LoadHTML() without a URL has an opaque origin, so origin patterns never match it.
  • Subframes are excluded unless requested. Pass dom::AllFrames in flags to deliver listeners to subframe documents and run OnDOMReady() for each frame's document.
  • Malformed rules cancel the attachment. If any rule fails to parse, AttachTo() returns false, logs a warning explaining the failure, and leaves the View unchanged.

Configure origin rules and frame targeting through AttachOptions when attaching the set:

bool attached = ui.AttachTo(view.get(), {
.flags = dom::AllFrames,
.origin_rules = { "https://*.mygame.com", "file://*" } });

For decisions origin rules can't express (such as checking a user setting or allowing an opaque origin), see dom::SetInjectionFilter() and dom::InjectionRequest.

Object Lifetime and Cleanup

Calling DetachFrom() removes the whole set from a View immediately, though individual registrations can't be removed on their own.

Destroying a dom::Triggers instance automatically detaches it from every View and stops its listeners right away. Storing the set as a member of the class whose methods its callbacks invoke ensures the listeners never outlive the surrounding object:

class Hud {
public:
explicit Hud(View* view) {
ui_.On("#close", "click", [this] { Dismiss(); });
if (!ui_.AttachTo(view))
Log("an origin rule failed to parse");
}
private:
void Dismiss() {}
dom::Triggers ui_;
};
Web-page container rendered to an offscreen surface.
Definition View.h:483
Dismiss
Auto-dismiss policy for floating panels and popup windows.
Definition Options.h:27

Back-Forward Cache Restores

When a page returns from the back-forward cache (Config::page_cache_size above 0), the library restores its event listeners before the pageshow event fires. Hooks registered with OnDOMReady() don't run again because the document was parsed during the initial load.

Register an OnRestore() hook for tasks that must run every time a cached page reappears:

ui.OnRestore([](dom::Document document) {
document.getElementById("status").textContent = "Welcome back";
});
void OnRestore(F &&callback)
Add a hook that runs each time a page that gets the set is restored from the back-forward cache (Conf...
Definition Triggers.h:440

Choosing Between Triggers and addEventListener

Choose between dom::Triggers and Element::addEventListener() based on whether the listeners belong to one page or the whole View:

  • dom::Triggers persists across navigations and cache restores. Use it for interface elements that must remain active across page loads or multiple Views.
  • Element::addEventListener() attaches to a single page's elements. Direct listeners belong to one document and are gone after a back-forward restore or navigation.
See also
dom::AttachOptions, dom::SetInjectionFilter(), dom::InjectionRequest, ultralight::OriginRules, dom::Element::On(), dom::EventListener

Static Public Member Functions

static Triggers Adopt (ULDOMTriggers handle)
 Wrap a C handle you own, taking ownership of it.
static Triggers FromBorrowed (ULDOMTriggers handle)
 Wrap a C handle someone else owns, without owning the set (eg, the triggers member of a dom::InjectionRequest).

Public Member Functions

 Triggers ()
 Create a new set of DOM listeners.
 Triggers (const Triggers &)=delete
Triggers & operator= (const Triggers &)=delete
 Triggers (Triggers &&other) noexcept
 Move constructor (other becomes empty).
Triggers & operator= (Triggers &&other) noexcept
 Move assignment (releases the set this object held, then takes over other's).
 ~Triggers ()
 Release this object's reference to the set.
 operator bool () const
 Whether or not this object holds a set (false after a move or LeakRef(), or when it wraps NULL).
template<typename F>
bool On (std::string_view selector, std::string_view type, F &&callback, EventListenerFlags flags=EventListenerFlags::None)
 Add a listener for events on elements matching a CSS selector.
template<typename C, typename M>
requires (std::is_class_v<C> && std::is_member_function_pointer_v<M> && !LockableHolder<C>)
bool On (std::string_view selector, std::string_view type, C &receiver, M method, EventListenerFlags flags=EventListenerFlags::None)
 Add a selector listener that calls a member function on a borrowed receiver (no forwarding lambda needed):
template<typename H, typename M>
requires (LockableHolder<H> && std::is_member_function_pointer_v<M>)
bool On (std::string_view selector, std::string_view type, H holder, M method, EventListenerFlags flags=EventListenerFlags::None)
 Add a selector listener that calls a member function through a holder (a shared_ptr, a weak_ptr, or a custom smart pointer with a HolderTraits specialization).
template<typename F>
void OnDOMReady (F &&callback)
 Add a hook that runs on each page that gets the set, once its document has finished parsing.
template<typename F>
void OnRestore (F &&callback)
 Add a hook that runs each time a page that gets the set is restored from the back-forward cache (Config::page_cache_size > 0).
bool AttachTo (View *view, const AttachOptions &options={})
 Attach this set to a View.
void DetachFrom (View *view)
 Detach this set from a View.
ULDOMTriggers raw () const
 Get the C handle, for passing to the <Ultralight/CAPI/CAPI_DOMTriggers.h> functions.
ULDOMTriggers LeakRef ()
 Give up ownership of the C handle and return it.

Constructor & Destructor Documentation

◆ Triggers() [1/3]

Triggers ( )
inline

Create a new set of DOM listeners.

◆ Triggers() [2/3]

Triggers ( const Triggers & )
delete

◆ Triggers() [3/3]

Triggers ( Triggers && other)
inlinenoexcept

Move constructor (other becomes empty).

Parameters
otherThe Triggers to move from.

◆ ~Triggers()

~Triggers ( )
inline

Release this object's reference to the set.

Note
Destroying the set detaches it from every View (see the class overview), unless it came from FromBorrowed() or another owning handle to it exists.

Member Function Documentation

◆ Adopt()

Triggers Adopt ( ULDOMTriggers handle)
inlinestatic

Wrap a C handle you own, taking ownership of it.

Parameters
handleA handle from the C API that you would otherwise destroy with ulDestroyDOMTriggers() (NULL gives an empty object).
Returns
Returns a Triggers that releases handle when it's done.

◆ AttachTo()

bool AttachTo ( View * view,
const AttachOptions & options = {} )
inlinenodiscard

Attach this set to a View.

The listeners are added to the View's current page (if its document has finished parsing and the origin rules allow it) and to every page the View loads afterward. The View keeps the set attached until you detach it or destroy this Triggers instance. Attaching again updates the flags and origin rules for later pages.

// Your own content, subframes included:
if (!ui.AttachTo(view.get(), { .flags = dom::AllFrames }))
Log("the attach failed");
Parameters
viewThe View to attach to.
optionsThe attach flags and the origin rules for the pages that get the listeners (see AttachOptions).
Returns
Returns true on success, or false if view is nullptr, this object holds no set, a flag is unknown, or a rule failed to parse. Nothing changes then. An unknown flag or a rule that failed to parse also logs a warning that says why.

◆ DetachFrom()

void DetachFrom ( View * view)
inline

Detach this set from a View.

The listeners are removed from the View's pages right away, and no later page gets them.

Parameters
viewThe View to detach from.
Note
If you attach the set again, the current page gets it again (and its DOM-ready hooks run again there).

◆ FromBorrowed()

Triggers FromBorrowed ( ULDOMTriggers handle)
inlinestatic

Wrap a C handle someone else owns, without owning the set (eg, the triggers member of a dom::InjectionRequest).

The result works like any Triggers, but destroying it never detaches the set, and it doesn't keep the set attached once its owners are gone.

Parameters
handleThe borrowed handle (NULL gives an empty object).
Returns
Returns a Triggers with its own (non-owning) reference, so you can keep it after the callback. Its raw() is a different handle than handle.

◆ LeakRef()

ULDOMTriggers LeakRef ( )
inline

Give up ownership of the C handle and return it.

This object becomes empty.

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

◆ On() [1/3]

template<typename C, typename M>
requires (std::is_class_v<C> && std::is_member_function_pointer_v<M> && !LockableHolder<C>)
bool On ( std::string_view selector,
std::string_view type,
C & receiver,
M method,
EventListenerFlags flags = EventListenerFlags::None )
inline

Add a selector listener that calls a member function on a borrowed receiver (no forwarding lambda needed):

ui.On("#save", "click", toolbar, &Toolbar::OnSave);
Parameters
selectorThe CSS selector to match (eg, #save).
typeThe event type to listen for (eg, click).
receiverThe object to call method on. You must keep it alive until this Triggers is destroyed or the set is detached from every View.
methodThe member function to call, taking (dom::Event, dom::Element matched), (dom::Element matched), or ().
flagsThe registration options (see EventListenerFlags).
Returns
Returns true if the listener was added (see the callable overload).

◆ On() [2/3]

template<typename F>
bool On ( std::string_view selector,
std::string_view type,
F && callback,
EventListenerFlags flags = EventListenerFlags::None )
inline

Add a listener for events on elements matching a CSS selector.

On every page that gets the set, the event target and its ancestors are tested against selector, and the callback fires with the nearest match. This covers elements added to the page later too (it works like Element::On() on the whole document).

Parameters
selectorThe CSS selector to match (eg, #save).
typeThe event type to listen for (eg, click).
callbackThe callable to invoke, taking (dom::Event, dom::Element matched), (dom::Element matched), or ().
flagsThe registration options (see EventListenerFlags).
Returns
Returns true if the listener was added, or false if it wasn't (eg, this object is empty, or selector is malformed). On false, the library destroys its copy of callback. You can ignore the result, since the library logs a warning for a refused selector.
Note
Events that don't bubble (eg, focus) reach the listener only with dom::Capture. A wheel listener is passive unless you pass dom::NotPassive.
Note
With dom::Once, the first type event that reaches the document uses up the listener on that page, even if no element matches.
Note
Before a Renderer exists, only an empty selector is refused here. Each page checks the selector when it gets the set instead, and skips a malformed one with a warning.

◆ On() [3/3]

template<typename H, typename M>
requires (LockableHolder<H> && std::is_member_function_pointer_v<M>)
bool On ( std::string_view selector,
std::string_view type,
H holder,
M method,
EventListenerFlags flags = EventListenerFlags::None )
inline

Add a selector listener that calls a member function through a holder (a shared_ptr, a weak_ptr, or a custom smart pointer with a HolderTraits specialization).

The holder is locked around each delivery, and an expired holder skips the delivery silently (see LockableHolder).

Parameters
selectorThe CSS selector to match (eg, #save).
typeThe event type to listen for (eg, click).
holderThe holder to lock and call the member on.
methodThe member function to call, taking (dom::Event, dom::Element matched), (dom::Element matched), or ().
flagsThe registration options (see EventListenerFlags).
Returns
Returns true if the listener was added (see the callable overload).

◆ OnDOMReady()

template<typename F>
void OnDOMReady ( F && callback)
inline

Add a hook that runs on each page that gets the set, once its document has finished parsing.

The hook runs after the set's listeners were added to the page, with or without JavaScript enabled. With dom::AllFrames it also runs for each subframe's document. It doesn't run when a page is restored from the back-forward cache (see OnRestore()).

Parameters
callbackThe callable to invoke, taking (dom::Document) or ().

◆ OnRestore()

template<typename F>
void OnRestore ( F && callback)
inline

Add a hook that runs each time a page that gets the set is restored from the back-forward cache (Config::page_cache_size > 0).

The hook runs after the set's listeners were added to the page again, and before the page's pageshow event. It never runs on a normal load.

Parameters
callbackThe callable to invoke, taking (dom::Document) or ().

◆ operator bool()

operator bool ( ) const
inlineexplicit

Whether or not this object holds a set (false after a move or LeakRef(), or when it wraps NULL).

◆ operator=() [1/2]

Triggers & operator= ( const Triggers & )
delete

◆ operator=() [2/2]

Triggers & operator= ( Triggers && other)
inlinenoexcept

Move assignment (releases the set this object held, then takes over other's).

Parameters
otherThe Triggers to move from.
Returns
Returns this object.

◆ raw()

ULDOMTriggers raw ( ) const
inline

Get the C handle, for passing to the <Ultralight/CAPI/CAPI_DOMTriggers.h> functions.

Returns
Returns the handle (NULL if this object holds no set). This object still owns it, so don't destroy it.

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