Player Methods

Imperative methods available via the player ref.

Overview

While most interactions are handled through props and callbacks, you can also control the player imperatively using a ref. This is useful for building custom controls, triggering actions from external UI, and advanced integrations.

Current Status

Imperative Ref API
The player exposes a comprehensive imperative API via a React ref covering playback, variables, actions, scenes, objects, and viewer preferences.

The player currently supports:

  • Props: Configure via src, metadata, objectGroups, etc.
  • Callbacks: React to events via onEngineReady, onSceneChange, onPlaybackRestricted
  • Actions: The engine executes actions defined in rules and plugin event handlers

See the Props Reference for currently available options.

Ref API

Access player methods through a React ref:

Using the Ref

Player ref usage
1import { useRef } from 'react';
2import { MP4EPlayer, type MP4EPlayerRef } from '@mp4e/react';
3import '@mp4e/react/styles.css';
4
5function App() {
6 const playerRef = useRef<MP4EPlayerRef>(null);
7
8 const handlePlayPause = () => {
9 if (playerRef.current?.isPaused()) {
10 playerRef.current.play();
11 } else {
12 playerRef.current?.pause();
13 }
14 };
15
16 const handleSeekTo10Seconds = () => {
17 playerRef.current?.seek(10);
18 };
19
20 const handleLogState = () => {
21 console.log('t=', playerRef.current?.getCurrentTime());
22 console.log('frame=', playerRef.current?.getCurrentFrame());
23 };
24
25 return (
26 <div>
27 <MP4EPlayer
28 ref={playerRef}
29 src="/video.mp4"
30 onEvent={(event) => { if (event === 'state:ready') console.log('Ready!'); }}
31 />
32
33 <div className="controls">
34 <button onClick={handlePlayPause}>Play/Pause</button>
35 <button onClick={handleSeekTo10Seconds}>Seek to 10s</button>
36 <button onClick={handleLogState}>Log state</button>
37 </div>
38 </div>
39 );
40}

Playback Methods

Control video playback programmatically.

play()async

Starts or resumes video playback.

Returns: Promise<void>

await playerRef.current?.play();
pause()

Pauses video playback.

Returns: void

playerRef.current?.pause();
seek(time)(time: number)

Seeks to the specified time in seconds.

Returns: void

playerRef.current?.seek(30.5);
seekToFrame(frame)(frame: number)

Seeks to the specified frame number. The player seeks to the middle of the frame, so the browser presents that frame rather than the one before it.

Returns: void

playerRef.current?.seekToFrame(750);
seekSilently(timeSeconds)(timeSeconds: number)

Seeks without triggering engine seeked rules (prevents loops).

Returns: void

playerRef.current?.seekSilently(12.0);
setPlaybackRate(rate)(rate: number)

Sets the playback speed. Range: 0.25 to 4.0.

Returns: void

playerRef.current?.setPlaybackRate(1.5);
setVolume(volume)(volume: number)

Sets the volume level. Range: 0.0 to 1.0.

Returns: void

playerRef.current?.setVolume(0.8);
mute()

Mutes audio.

Returns: void

playerRef.current?.mute();
unmute()

Unmutes audio.

Returns: void

playerRef.current?.unmute();

State Methods

Query current player state.

getCurrentTime()

Returns the current playback time in seconds.

Returns: number

const time = playerRef.current?.getCurrentTime(); // 30.5
getCurrentFrame()

Returns the current frame number.

Returns: number

const frame = playerRef.current?.getCurrentFrame(); // 763
getDuration()

Returns the total video duration in seconds.

Returns: number

const duration = playerRef.current?.getDuration(); // 120
isPaused()

Returns whether the video is paused.

Returns: boolean

const paused = playerRef.current?.isPaused(); // false
isMuted()

Returns whether the audio is muted.

Returns: boolean

const muted = playerRef.current?.isMuted(); // false
getVolume()

Returns the current volume level (0-1).

Returns: number

const volume = playerRef.current?.getVolume(); // 0.8
getPlaybackRate()

Returns the current playback rate.

Returns: number

const rate = playerRef.current?.getPlaybackRate(); // 1.0
isFullscreen()

Returns whether the player is in fullscreen mode.

Returns: boolean

const fs = playerRef.current?.isFullscreen(); // false

Metadata & State

Access and reload metadata, check a document for problems before applying it, see what runs for its events, and query playback loop boundaries.

reloadMetadata(newMetadata?)(newMetadata?: MP4EMetadata | null)

Reload metadata without full destroy/reinit. When the engine is already initialized, this performs a soft reload that preserves DOM (no iframe recreation or visible flash) and carries playback position, variable values, running timers, counters, and the current scene through the swap for ids that still exist in the new document. On a file that streams its object tracking, the tracking already loaded is kept too when the new document's tracking is unchanged (as on every overrides change), so nothing is fetched again. If newMetadata is omitted, the current metadata prop is re-applied. The returned promise resolves once the new document has been applied and rendered — await it when you need to know the swap has landed, or ignore it for fire-and-forget calls.

Returns: Promise<void>

// Soft reload with updated metadata await playerRef.current?.reloadMetadata(updatedMetadata); // Re-apply current metadata prop playerRef.current?.reloadMetadata();
getEffectiveMetadata()

Returns the view of the loaded document, with your overrides already merged in — the same value the metadata:loaded event carries. The view holds schemaVersion, videoDetails (fps, width, height, durationSeconds), layers (id, name, order and their overlays — each overlay with id, layerId, type, name, overlayCategory, position, size, config, opacity, zIndex), audioTracks, media, thumbnails, objectCount, timeline.mode ('chunked' when the file streams its object tracking, else 'full') and tappableObjects (the ids of objects a tap opens a card on or runs a click rule for; a tap on one does not reveal the player's controls). It does not include objects, variables, rules, scenes or plugins — read variables with getVariable() / getVariables(). Returns null until a document has been loaded.

Returns: MetadataView | null

const view = playerRef.current?.getEffectiveMetadata(); if (view) { console.log('Frame rate:', view.videoDetails.fps); console.log('Layers:', view.layers.map((layer) => layer.name)); console.log('Overlays:', view.layers.flatMap((layer) => layer.overlays).map((o) => o.id)); console.log('Tracked objects:', view.objectCount); }
diagnose(metadata)(metadata: MP4EMetadata)async

Runs the engine's diagnostics over a metadata document and returns every problem it would hit or silently skip when running it — dangling references, unparseable conditions or variables, unknown types, impossible frame ranges, structural shapes the engine drops, plugin config that contradicts the plugin's schema, and templates that resolve to nothing. The document is checked in isolation: nothing is loaded and player state is untouched, so this is safe to call on a candidate document before applying it. An empty array means the document is clean. Each finding carries a severity (error / warning / info), a stable namespaced code and dotted path, a human-readable message, the owning entity, and — where one exists — suggested replacements. The findings from the document the player actually loaded arrive on their own via the metadata:diagnostics event.

Returns: Promise<DiagnosticFinding[]>

const findings = (await playerRef.current?.diagnose(candidateMetadata)) ?? []; const blocking = findings.filter(f => f.severity === 'error'); if (blocking.length) { console.table(blocking.map(f => ({ code: f.code, path: f.path, hint: f.suggestions?.[0] }))); }
describeHandlers(metadata, ref)(metadata: MP4EMetadata, ref: HandlerRef)async

Answers what runs for one thing's events in a metadata document: for each event of an overlay, object, object group, scene, layer, card or the project, every handler list and rule that runs for it at every level, in the order the player runs them, where each is stored, and why a stored one does not run. Like diagnose, it reads only the document you pass: nothing is loaded and player state is untouched. Use it to build an event editor of your own, or to see why a handler does or does not fire. It rejects when the player is not ready or when the engine running in the player cannot answer (an older engine embedded in a file); a ref it cannot answer is not a rejection but an answer with an error (below).

Returns: Promise<HandlerDescription>

import type { HandlerDescription } from '@mp4e/react'; const answer: HandlerDescription = await playerRef.current!.describeHandlers( candidateMetadata, { type: 'object', id: 'obj_chair', event: 'onClick' }, ); if (answer.error) { console.warn(answer.error.code, answer.error.message); // e.g. ref.unknown } else { for (const ev of answer.events) { for (const entry of ev.entries) { console.log(ev.event, entry.level, entry.owner, entry.runs ? 'runs' : 'skipped: ' + entry.reason); } } } // onClick project { type: 'project' } runs // onClick objectGroup { type: 'objectGroup', id: 'products' } runs // onClick object { type: 'object', id: 'obj_chair' } runs

The ref

The types HandlerRef, HandlerDescription, HandlerEventDescription and HandlerEntry are exported by @mp4e/react.

PropTypeDefaultDescription
{ type: 'overlay' | 'object' | 'objectGroup' | 'scene' | 'layer', id }HandlerRef-One overlay, object, object group, scene or layer, by id.
{ type: 'project' }HandlerRef-The project's own events (playback, input, variables, plugin events and the project rules keyed to one thing).
{ type: 'binding', owner, index, objectId? }HandlerRef-A card: the display binding at index in its owner's list of cards. owner is { type: 'objectGroup', id }, { type: 'object', id } or { type: 'project' } (the project's default cards). With objectId, the answer lists every level that runs for that object's card; without it, the project level and this binding.
eventstring-Optional on every ref: answer one event only. Its name, an alias of it (onMouseEnter for onHover) or a full plugin event key (plugin:<namespace>:<identifier>:<event>).

The answer

{ ref, events }: the thing's events in a fixed order (its own events, then, for an overlay, the events its plugin emits, then any other stored key), each with:

PropTypeDefaultDescription
eventstring-The event: its canonical name (onClick, onVisible…) or the full plugin event key. An event stored under an alias is listed once, under its canonical name.
knownboolean-false for a stored key that is not an event of this thing (it never runs).
entriesHandlerEntry[]-Every handler list and rule stored for this event, at every level, in the order the player runs them; the ones that do not run are listed too, with the reason.
writeToArray<string | number>-The document path where a new plain action list for this event belongs: the spot the player reads. An editor writes there.
writeRulesToArray<string | number>-The document path where a new rule for this event belongs.
pluginInstalledboolean-Project plugin events only: false when the plugin is not in the project's plugins, so nothing for it runs.
engineKeysstring[]-The engine's internal keys for this event. For debugging only; do not store them.

Each entry:

PropTypeDefaultDescription
level'project' | 'objectGroup' | 'object' | 'overlay' | 'scene' | 'layer' | 'binding'-The level the entry is written at.
owner{ type, id? } | { type: 'binding', owner, index }-The thing the entry belongs to.
scope'all' | 'this'-all: a project-level entry for a plugin event, which runs for every instance of that plugin. this: everything else.
pathArray<string | number>-Where the entry is stored in the document (numbers are array indexes). Unique per entry.
form'actions' | 'rule'-actions: a plain action list, which runs every time. rule: a rule with an id, optional conditions, a name and an on/off switch.
ruleIdstring | null-The rule's id (a plain list gets one generated by the engine; never store a generated id). null when the entry is not registered.
name, enabled, priority, feature-The rule's name, whether it is on, its priority and the feature that added it, when set.
hasConditionsboolean-Whether the rule has conditions.
actionCountnumber-How many actions the entry holds.
storedAsstring-The key it is stored under, which shows an alias (onMouseEnter for an onHover entry).
runsboolean-true when the player runs this entry for the event. The entries with runs: true are exactly what fires, in this order.
reasonstring | null-Why an entry does not run (null when it runs). See the table below.

Why an entry does not run:

PropTypeDefaultDescription
shadowed-Another list for this event on the same thing is the one the player reads; this one is never run.
disabled-The rule is switched off.
unknownEvent-The key it is stored under is not an event of this thing.
empty-An empty list. It runs nothing, and it is still the list the player reads, so a later list for the same event does not run.
noId-A rule without an id. The player drops it.
keyNotChosen-A project rule under one spelling of a plugin event (the plugin's key or its id) that the player does not evaluate, because another spelling of the same event has rules.

A ref the engine cannot answer gives { ref, events: [], error }, where error has the shape of a diagnose finding (severity: 'error', code, message) and code is ref.malformed (not a valid ref: no or unknown type, a binding without owner or index), ref.unknown (no such thing, binding or object in the document) or parse.envelope (the document does not load).

describeVariables(metadata)(metadata: MP4EMetadata)async

Lists every variable of a metadata document as the player runs it: the creator's own and those the plugins declare, each with its id at runtime, scope, owner, whether it is read-only, the value it starts with, where it is declared, and the variable findings that name it. A variable a plugin keeps per use (scope instance) comes with an id pattern and the uses the document shows: one per overlay, and one per object for an overlay bound to a group or a card. Like diagnose, it reads only the document you pass: nothing is loaded and player state is untouched. It rejects when the player is not ready or when the engine running in the player cannot answer (an older engine embedded in a file).

Returns: Promise<VariablesDescription>

import type { VariablesDescription } from '@mp4e/react'; const { variables, findings }: VariablesDescription = await playerRef.current!.describeVariables(candidateMetadata); for (const v of variables) { console.log(v.id ?? v.idPattern, v.scope, v.owner, v.readOnly ? 'read-only' : 'writable'); } // taxRate project { type: 'document' } read-only // mp4e:cart:total plugin { type: 'plugin', key: 'mp4e:cart' } read-only // mp4e:quiz:score@<instance> instance { type: 'plugin', key: 'mp4e:quiz' } read-only console.table(findings.map(f => ({ code: f.code, path: f.path })));

Each variable: scope is project (the creator's own), plugin, instance or global; owner is { type: 'document' } or { type: 'plugin', key }. A read-only variable changes only by its owner (a plugin's own script) and by the host; a read-only variable of the creator is a constant, which takes its document's value again when your overrides change. The findings are variable.readOnlyWrite (a stored rule writes a read-only variable; the write will be refused), variable.readOnlyGlobal, variable.globalConflict (two declarations of one global disagree on type), variable.shadowedCopy (a project variable copies a plugin's own variable) and variable.unknownScope. The types are exported by @mp4e/react.

getPlaybackStart()

Returns the playback loop start time in seconds. This is the time the video will seek to when looping or when setPlaybackStart has been applied via rules.

Returns: number

const loopStart = playerRef.current?.getPlaybackStart(); // 0
getPlaybackEnd()

Returns the playback loop end time in seconds. Returns -1 if no end boundary is set (plays to the end of the video).

Returns: number

const loopEnd = playerRef.current?.getPlaybackEnd(); // -1 (no limit)

Variable Methods

Read and modify engine variables. The setVariable method triggers the engine's rules pipeline, so any rules listening for variable changes will fire.

setVariable(variableId, value)(variableId: string, value: any)

Sets a variable value at runtime. This goes through the engine, so any rules with variable-change conditions will trigger. Plugins listening via onVariableChange will also be notified. The change applies at once — while the video is paused the current frame repaints, so a zone or overlay that reads the variable updates immediately.

Returns: void

// Set a simple variable playerRef.current?.setVariable('cartCount', 5); // Set an object variable playerRef.current?.setVariable('selectedProduct', { id: 'prod_123', name: 'Blue T-Shirt', price: 29.99, });
getVariable(variableId)(variableId: string)

Returns the current value of a variable. Returns undefined if the variable doesn't exist.

Returns: any

const score = playerRef.current?.getVariable('score'); // 42 const name = playerRef.current?.getVariable('userName'); // 'Alice'
getVariables()

Returns a snapshot of all variables as a plain object. Keys are variable IDs, values are current values. It holds every variable of the loaded document from the metadata:loaded event on, so a metadata:loaded handler can read it — for example, to see whether the video takes a variable your page sets.

Returns: Record<string, any>

const vars = playerRef.current?.getVariables(); console.log(vars); // { score: 42, userName: 'Alice', cartCount: 3 }

Action Methods

Execute actions and send events programmatically from host code.

executeAction(action)(action: any)

Executes a single action programmatically. Convenience wrapper around executeActions.

Returns: void

playerRef.current?.executeAction({ type: 'pause' }); playerRef.current?.executeAction({ type: 'showOverlay', overlayId: 'promo-banner' });
executeActions(actions)(actions: any[])

Executes an array of actions programmatically. Actions are processed through the engine's action executor, so all engine-side effects (variable changes, rule triggers, playback events) apply as if the actions were triggered by a rule.

Returns: void

playerRef.current?.executeActions([ { type: 'pause' }, { type: 'showOverlay', overlayId: 'promo-banner' }, { type: 'setVariable', variableId: 'promoShown', value: true }, ]);
notify(event, data?)(event: string, data?: any)

Sends an event into the engine. This is the universal event entry point — any rules listening for the specified event will fire. Useful for custom host-originated events that drive rule logic.

Returns: void

// Notify the engine of a custom event playerRef.current?.notify('custom:purchase', { productId: 'abc', amount: 29.99, }); // Notify of a standard event playerRef.current?.notify('overlay:click', { overlayId: 'cta-button', });

Scene Methods

Navigate between scenes and query scene state.

goToScene(sceneId)(sceneId: string)

Navigates to the specified scene. The engine resolves the scene's start time and seeks the video accordingly. Any scene exit/enter rules will fire.

Returns: void

playerRef.current?.goToScene('chapter-2'); playerRef.current?.goToScene('quiz-scene');
setPlaybackPath(groupId)(groupId: string) => Promise<PlaybackPathResult>

Plays only the scenes of one scene group. The progress bar shows the path's duration, every seek stays inside the path, gaps between scenes are skipped, and playback pauses at the end of the last scene. Authored rules keep seeing media time; controls see presentation time.

Returns: Promise<{ ok: true, state } | { ok: false, error: { code, message, groupId } }>

const res = await playerRef.current?.setPlaybackPath('scenegroup_short'); if (!res?.ok) console.warn(res?.error.code); // playbackPath.invalidGroup | playbackPath.locked | playbackPath.emptyAfterBounds
clearPlaybackPath()() => Promise<PlaybackPathResult>

Returns to the full timeline. The playhead is not moved.

Returns: Promise<PlaybackPathResult>

await playerRef.current?.clearPlaybackPath();
getPlaybackPath()() => Promise<PlaybackPathState | null>

Current playback path: group id, revision, presentation duration and time, current scene, completed and locked flags, initiator, ranges and scenes.

Returns: Promise<PlaybackPathState | null>

const path = await playerRef.current?.getPlaybackPath(); console.log(path?.time, '/', path?.duration);
getSceneGroups()() => Promise<SceneGroupSnapshot[]>

Snapshot of every scene group in metadata order, disabled ones included. Each group carries its scenes (start time, exclusive end time, duration, and, when the video has been analysed, the summary of the chapter that overlaps it most — with the creator's corrections, and none from a chapter the creator hid or kept private), the duration of the group's combined scene ranges, and the scene currently active in that group (null for disabled groups).

Returns: Promise<SceneGroupSnapshot[]>

const groups = await playerRef.current?.getSceneGroups(); for (const g of groups ?? []) console.log(g.name, g.duration, g.activeSceneId);
getCurrentScene()

Returns the ID of the currently active scene, or null if no scene is active.

Returns: string | null

const sceneId = playerRef.current?.getCurrentScene(); console.log('Current scene:', sceneId); // 'chapter-1'

Ad Breaks

Run an ad (or any short break) in the middle of the video: the player pauses the video at its position, plays the break in the same video element, and resumes where it was. The player decides whether the break may run, under your config.interstitials policy and the creator's. See Ads in Video for the spec, the policy and the events.

requestInterstitial(spec)(spec: InterstitialSpec) => Promise<InterstitialRequestResult>

Asks for a break now. spec names the placement (preroll, midroll, postroll or other), a template plugin installed in the video (for example mp4e:ad-controls) and the ad video (src, width, height, durationSeconds), plus optional skippableAfter, maxSeconds, advertiser and declared. The answer is { ok: true, breakId }, or { ok: false, reason } — invalid, busy, depth, disabled, initiator, source, placement, template, window, spacing, cap, notReady (the player has not started) or error. The break then reports through the interstitial:* events.

Returns: Promise<{ ok: true, breakId: string } | { ok: false, reason: string }>

const answer = await playerRef.current?.requestInterstitial({ placement: 'midroll', template: { plugin: 'mp4e:ad-controls', config: { clickThroughUrl: 'https://acme.example/' } }, media: { src: 'https://cdn.example.com/acme-15s.mp4', width: 1280, height: 720, durationSeconds: 15 }, skippableAfter: 5, advertiser: 'Acme Shoes', }); if (!answer?.ok) console.info('No break:', answer?.reason);
cancelInterstitial()() => Promise<void>

Ends the break that is running; the video resumes where it was and interstitial:ended reports reason cancelled. Does nothing when no break is running.

Returns: Promise<void>

await playerRef.current?.cancelInterstitial();
setProgramme()(programme: { start, end?, title?, file?, resumes? } | null) => void

On a live stream: the programme on air. Time in the player then counts from its start, for every viewer. file names the exported MP4E file whose interactivity is this programme's; null removes the programme. See Streams (HLS and DASH).

Returns: void

playerRef.current?.setProgramme({ start: '2026-11-11T21:30:00Z', title: 'The News', file: 'https://cdn.example.com/the-news.mp4', });
getLiveState()() => Promise<LiveState>

On a live stream: whether the video is live, how far the viewer is behind, the clock in use, the date of the picture on screen (broadcastTime, epoch milliseconds) and the programme on air.

Returns: Promise<LiveState>

const state = await playerRef.current?.getLiveState(); if (state?.live) console.info('On screen now:', new Date(state.broadcastTime));
goLive()() => void

On a live stream: return the viewer to live. Nothing happens on a file, or when they are already there. During a session it ends the session.

Returns: void

playerRef.current?.goLive();
startSession()() => void

On a live stream, when the programme on air is a session video: the viewer takes part, from the programme's start, on their own time. Refused with action:blocked when no session is available (live:state says so in session.available).

Returns: void

playerRef.current?.startSession();
endSession()() => void

End the viewer's session: its state is discarded and they are back on live. Nothing happens when no session is on.

Returns: void

playerRef.current?.endSession();

Viewer Preferences

Control privacy and accessibility preferences for the current viewer. These preferences are passed to the engine and affect how plugins behave (e.g., respecting do-not-track, reduced motion, high contrast).

setViewerPreferences(prefs)(prefs: Record<string, any>)

Sets privacy and accessibility preferences for the viewer. Supported keys include doNotTrack, doNotShareIdentity, limitStorage (privacy) and reducedMotion, highContrast (accessibility). Preferences are sent to the engine and made available to plugins. With limitStorage, what the video keeps between visits lasts only until the tab closes and onStateSave is not called (see Configuration › Keeping State Between Visits).

Returns: void

playerRef.current?.setViewerPreferences({ doNotTrack: true, doNotShareIdentity: false, limitStorage: true, reducedMotion: true, highContrast: false, });
getViewerPreferences()

Returns the current viewer preferences object. Returns an empty object if no preferences have been set.

Returns: Record<string, any>

const prefs = playerRef.current?.getViewerPreferences(); console.log('Do Not Track:', prefs.doNotTrack); // true console.log('Reduced Motion:', prefs.reducedMotion); // true

Display ControlComing Soon

Programmatically show and hide object and overlay display popups. These methods are available on the underlying engine but not yet exposed on the player ref.

showObjectDisplay(objectId?, eventType?, bbox?)(objectId?: string, eventType?: string, bbox?: number[])

Programmatically show an object's display overlay (e.g., tooltip, product card). The eventType determines which display plugin to use (e.g., 'hovered', 'clicked'). The bbox is an optional bounding box [x, y, w, h] in video coordinates for positioning. Showing a display that is already open shows it again.

Returns: void

// Show the hover display for a specific object playerRef.current?.showObjectDisplay('obj_chair_1', 'hovered', [100, 200, 50, 50]); // Show the click display playerRef.current?.showObjectDisplay('obj_chair_1', 'clicked');
hideObjectDisplay(objectId?)(objectId?: string)

Hide an object's display overlay. If objectId is omitted, hides all object displays. A display that opens by itself while its object is on screen (a 'visible' binding) stays closed after this until its object leaves the screen and comes back.

Returns: void

playerRef.current?.hideObjectDisplay('obj_chair_1');
showOverlayDisplay(overlayId?, eventType?, boundObjectId?, bbox?)(overlayId?: string, eventType?: string, boundObjectId?: string | null, bbox?: number[])

Show an overlay's display popup. For group-bound overlays, provide the boundObjectId to target a specific instance. The bbox provides positioning context in video coordinates.

Returns: void

// Show a display for a specific overlay playerRef.current?.showOverlayDisplay('hotspot-1', 'clicked'); // Show for a group-bound overlay instance playerRef.current?.showOverlayDisplay('hotspot-1', 'clicked', 'obj_lamp_3', [300, 150, 80, 60]);
hideOverlayDisplay(overlayId?, boundObjectId?, eventType?)(overlayId?: string, boundObjectId?: string | null, eventType?: string)

Hide an overlay's display popup. For group-bound overlays, provide the boundObjectId to target a specific instance.

Returns: void

playerRef.current?.hideOverlayDisplay('hotspot-1', null, 'clicked');

Layout & Positioning

Inspect and modify overlay layout, coordinate transforms, and container elements.

updateOverlayStyle(overlayId, styles)(overlayId: string, styles: { x?: number; y?: number; width?: number; height?: number })

Move and/or resize the overlay the viewer sees, at once, without changing the document — for live feedback such as dragging an overlay in an editor. Values are video-native pixels; x and y are the overlay's top-left corner. Only the given properties change, and the overlay's scale and rotation are kept. The player holds this placement over every other placement of the overlay — the document's, keyframes, object following, and position or size a rule sets at runtime (setOverlayStyle) — until the document next changes (reloadMetadata or updateOverrides) or you call clearOverlayStyle. To keep a new placement, write it into the document, which also ends the hold; if you end without changing the document, call clearOverlayStyle. On a group-bound overlay, every per-object copy takes the width and height only; its position stays on its object.

Returns: void

// Move an overlay playerRef.current?.updateOverlayStyle('cta-button', { x: 200, y: 100 }); // Resize an overlay playerRef.current?.updateOverlayStyle('sidebar', { width: 300, height: 400 }); // Move and resize simultaneously playerRef.current?.updateOverlayStyle('panel', { x: 50, y: 50, width: 250, height: 150 });
clearOverlayStyle(overlayId?)(overlayId?: string)

Release the placement updateOverlayStyle holds for one overlay, or for every overlay when called without an ID. The overlay returns at once to where the player would otherwise place it (document, keyframes, object following, rule styles), paused or playing. Call it when a drag or preview ends without a document change.

Returns: void

// A drag preview the user cancelled playerRef.current?.updateOverlayStyle('cta-button', { x: 200, y: 100 }); playerRef.current?.clearOverlayStyle('cta-button'); // Release every held overlay playerRef.current?.clearOverlayStyle();
getOverlayPositions()

Returns the rendered box of each overlay the player has placed, as a Map from overlay ID to { x, y, width, height } in video-native pixels (x and y are the top-left corner), plus originX and originY: the point the player scales and rotates the box about, in pixels from its top-left (optional). For a content-sized (Auto) overlay the box is the part that shows — only what its plugin draws — and the origin is the top-left of its laid-out content, so it can lie outside the box; for a fixed-size overlay the origin is the box's centre. Listen for overlay:presenceChanged to learn when an Auto overlay's box changes. Group-bound overlays' per-object copies are not included, nor are replacement zones, which are drawn on the video rather than placed as boxes.

Returns: Map<string, RenderedOverlayPosition>

const positions = playerRef.current?.getOverlayPositions(); if (positions) { for (const [id, pos] of positions) { console.log(id, pos); } }
getEngineVersion()

Returns the version of the engine this player loaded — the one embedded in the video file when the player uses it, else the one bundled with the package — or null before an engine is loaded. Useful in logs and bug reports, to know which engine played a video.

Returns: string | null

const version = playerRef.current?.getEngineVersion(); console.log('Engine:', version ?? 'not loaded yet');
getVideoDisplayTransform()

Returns the current video-to-screen coordinate transform. This describes how video-native pixel coordinates map to screen coordinates, accounting for letterboxing, scaling, and aspect ratio. Returns null if the video element is not yet ready.

Returns: VideoDisplayTransform | null

const transform = playerRef.current?.getVideoDisplayTransform(); if (transform) { console.log('Scale:', transform.scaleX, transform.scaleY); console.log('Offset:', transform.offsetX, transform.offsetY); }
getOverlayContainerRef()

Returns the overlay container DOM element. This is the div that contains all overlay iframes and positioned elements. Useful for advanced integrations that need to inject custom DOM alongside overlays.

Returns: HTMLDivElement | null

const container = playerRef.current?.getOverlayContainerRef(); if (container) { console.log('Overlay container dimensions:', container.offsetWidth, container.offsetHeight); }

Object Methods

Query tracked objects and their data.

getVisibleObjects()

Returns objects visible in the current frame, including their bounding boxes, polygons, custom data, and group memberships.

Returns: Array<{ id: string; bbox: number[]; polygon?: number[][]; data?: any; groupIds?: string[] }>

const objects = playerRef.current?.getVisibleObjects(); for (const obj of objects) { console.log(obj.id, obj.bbox, obj.data?.title); }
getObject(objectId)(objectId: string)

Returns object data from the registry by ID. This includes custom data fields defined in the object's group data schema. Returns null if the object doesn't exist.

Returns: any | null

const chair = playerRef.current?.getObject('obj_chair_1'); if (chair) { console.log(chair.label, chair.data?.price); }

Utility Methods

Fullscreen, metadata, and cleanup.

enterFullscreen()async

Enters fullscreen mode.

Returns: Promise<void>

await playerRef.current?.enterFullscreen();
exitFullscreen()async

Exits fullscreen mode.

Returns: Promise<void>

await playerRef.current?.exitFullscreen();
toggleFullscreen()async

Toggles fullscreen mode.

Returns: Promise<void>

await playerRef.current?.toggleFullscreen();
Full screen on iPhone
Safari and Chrome on iPhone cannot put a page element in full screen; their only full screen shows the bare video and drops every overlay. So there the player covers the screen itself: it rises above everything on your page (on iOS 17 and later, whatever the z-index or transform of its ancestors), keeps its overlays, plugins and controls, stays clear of the notch and home indicator, and locks the page from scrolling. Leaving full screen (the control, exitFullscreen(), or Escape) puts the player back and restores the page's scroll position; rotating the phone keeps playing where it was. isFullscreen(), the fullscreen:changed event and the {{isFullscreen}} value behave exactly as with real full screen. The browser's own address and tool bars stay visible: Apple gives web pages no way to hide them. iPad, Android and desktop browsers use real full screen.
getVideoElement()

Returns the underlying HTMLVideoElement (advanced use only).

Returns: HTMLVideoElement | null

const el = playerRef.current?.getVideoElement();
getCanvasElement()

Returns the overlay canvas element (advanced use only).

Returns: HTMLCanvasElement | null

const el = playerRef.current?.getCanvasElement();

Complete Example

All methods reference
1const playerRef = useRef<MP4EPlayerRef>(null);
2
3// Playback control
4await playerRef.current?.play();
5playerRef.current?.pause();
6playerRef.current?.seek(30);
7playerRef.current?.seekToFrame(750);
8playerRef.current?.setPlaybackRate(1.5);
9playerRef.current?.setVolume(0.8);
10playerRef.current?.mute();
11playerRef.current?.unmute();
12playerRef.current?.seekSilently(12.0);
13
14// Get state
15const time = playerRef.current?.getCurrentTime(); // 30.5
16const frame = playerRef.current?.getCurrentFrame(); // 763
17const duration = playerRef.current?.getDuration(); // 120
18const paused = playerRef.current?.isPaused(); // false
19const muted = playerRef.current?.isMuted(); // false
20const volume = playerRef.current?.getVolume(); // 0.8
21const rate = playerRef.current?.getPlaybackRate(); // 1.5
22const fullscreen = playerRef.current?.isFullscreen(); // false
23
24// Metadata & state
25const view = playerRef.current?.getEffectiveMetadata(); // the loaded document's view
26playerRef.current?.reloadMetadata(updatedMetadata);
27const loopStart = playerRef.current?.getPlaybackStart();
28const loopEnd = playerRef.current?.getPlaybackEnd();
29const findings = await playerRef.current?.diagnose(candidateMetadata);
30const handlers = await playerRef.current?.describeHandlers(candidateMetadata, { type: 'overlay', id: 'btn-buy' });
31
32// Variables
33playerRef.current?.setVariable('cartCount', 5);
34const score = playerRef.current?.getVariable('score'); // 42
35const allVars = playerRef.current?.getVariables(); // { score: 42, ... }
36
37// Actions
38playerRef.current?.executeAction({ type: 'pause' });
39playerRef.current?.executeActions([
40 { type: 'showOverlay', overlayId: 'promo-banner' },
41 { type: 'setVariable', variableId: 'promoShown', value: true },
42]);
43playerRef.current?.notify('custom:purchase', { productId: 'abc' });
44
45// Scenes
46playerRef.current?.goToScene('chapter-2');
47const scene = playerRef.current?.getCurrentScene(); // 'chapter-1'
48
49// Ad breaks
50const answer = await playerRef.current?.requestInterstitial(spec); // { ok: true, breakId } | { ok: false, reason }
51await playerRef.current?.cancelInterstitial();
52
53// Objects
54const visible = playerRef.current?.getVisibleObjects(); // [{ id, bbox, ... }]
55const chair = playerRef.current?.getObject('obj_chair_1'); // { label, data, ... }
56
57// Viewer preferences
58playerRef.current?.setViewerPreferences({
59 doNotTrack: true,
60 reducedMotion: true,
61});
62const prefs = playerRef.current?.getViewerPreferences();
63
64// Layout & positioning
65const transform = playerRef.current?.getVideoDisplayTransform();
66const positions = playerRef.current?.getOverlayPositions();
67const engineVersion = playerRef.current?.getEngineVersion();
68playerRef.current?.updateOverlayStyle('overlay-1', { x: 100, y: 200 });
69playerRef.current?.clearOverlayStyle('overlay-1');
70const container = playerRef.current?.getOverlayContainerRef();
71
72// Fullscreen
73await playerRef.current?.enterFullscreen();
74await playerRef.current?.exitFullscreen();
75await playerRef.current?.toggleFullscreen();
76
77// Elements (advanced)
78const videoEl = playerRef.current?.getVideoElement();
79const canvasEl = playerRef.current?.getCanvasElement();