Host Config & Security
Configure the permission model, action gating, plugin security, and content restrictions for the MP4E player.
Overview
MP4E uses a three-tier permission model that follows an intersection pattern: each layer can only restrict, never expand, what the previous layer allows. This ensures that no single party (creator, host, or viewer) can override the restrictions of another.
| Tier | Source | Controls |
|---|---|---|
| 1. Creator Restrictions | metadata.settings.restrictions | Author-declared limits embedded in the .mp4e file (e.g., sequential playback, blocked actions). Enforced by the engine even without host config. |
| 2. Host Config | config React prop | Sandbox actions, disable overlays/layers/plugins/rules, gate actions for approval, plugin security rules. |
| 3. Viewer Preferences | setViewerPreferences() at runtime | Privacy (doNotTrack, doNotShareIdentity, limitStorage) and accessibility (reducedMotion, highContrast). The viewer always has final say. |
// Three-tier permission model
// Each layer can only RESTRICT, never expand permissions.
// Tier 1: Creator restrictions (embedded in the .mp4e file)
metadata.settings.restrictions = {
sequential: true, // No seeking forward
actions: { download: false }
};
// Tier 2: Host config (React prop)
<MP4EPlayer
config={{
sandbox: { actions: { openUrl: false } },
gated: ['navigate'],
disabled: { layers: ['debug-layer'] }
}}
/>
// Tier 3: Viewer preferences (runtime, from player menu)
engine.setViewerPreferences({
doNotTrack: true,
reducedMotion: true
});download and the host blocks openUrl, then both are blocked at runtime. Neither party can re-enable what the other has restricted.MP4EConfig Reference
The config prop accepts an MP4EConfig object. It is passed to the WASM engine via setConfig() after setMetadata().
Sandbox
Block specific action types globally. Actions not listed are allowed by default.
| Prop | Type | Default | Description |
|---|---|---|---|
sandbox.actions | Record<string, boolean> | - | Block or allow specific action types. Keys are action type strings (e.g. "openUrl", "navigate"). Values: true = allowed, false = blocked. Any action type not listed is allowed by default (default-open model). Applies to every execution path, including viewer playback controls — sandboxing "pause" blocks pause regardless of whether a rule, a plugin, or the viewer requested it. A plugin's mp4e.openUrl counts as the "openUrl" action. Independently of this setting, openUrl and navigate open only http:, https:, mailto: and tel: URLs, and relative URLs resolved against the host page; any other URL is refused before it reaches gating. |
Disabled Content
Suppress specific creator content by ID. Disabled items are silently removed from the engine's working set.
| Prop | Type | Default | Description |
|---|---|---|---|
disabled.overlays | string[] | - | Array of overlay IDs to suppress. Matching overlays will not render. |
disabled.plugins | string[] | - | Array of plugin IDs (namespace:identifier, e.g. "mp4e:shopping-cart") to suppress. A disabled plugin is never created (no service, controls, or menu instance), overlays whose type is that plugin are not rendered, and its plugin API calls are refused with an error. Takes effect for API calls immediately; overlay filtering applies when metadata loads. |
disabled.layers | string[] | - | Array of layer IDs to suppress. All overlays within matching layers are hidden. |
disabled.rules | string[] | - | Array of rule IDs to suppress. Matching rules will not be evaluated or executed. |
disabled.actionTypes | string[] | - | Array of action type strings to suppress globally. Any action of a matching type will be silently dropped. |
Action Gating
Require host approval before executing certain action types. The engine pauses the action and invokes the onActionGate callback.
| Prop | Type | Default | Description |
|---|---|---|---|
gated | string[] | - | Action types that require host approval before execution. When an action of a listed type fires, the engine pauses it and invokes the onActionGate callback. The host must call resolve(true) to allow or resolve(false) to deny. |
gateTimeoutMs | number | 5000 | How long (in milliseconds) the engine waits for the host to call resolve() on a gated action before applying the timeout policy. |
gateTimeoutPolicy | 'allow' | 'deny' | 'deny' | What happens when the gate timeout expires without a resolve() call. "allow" lets the action proceed; "deny" silently drops it. |
Engine Source
A file can carry its own signed engine. The player prefers the embedded engine and falls back to the bundled engine, so playback always works. These options control that choice.
| Prop | Type | Default | Description |
|---|---|---|---|
engineSource | 'auto' | 'embedded' | 'bundled' | 'auto' | Which engine runs when a file carries its own embedded engine. 'auto' prefers the file's embedded engine and falls back to the bundled engine if it is missing or fails verification. 'embedded' forces the file's engine when present (still falling back on failure). 'bundled' always uses the bundled engine and ignores any embedded one. |
minEngineVersion | string | - | Reject an embedded engine below this version. A file whose embedded engine is older falls back to the bundled engine. |
revokedEngineVersions | string[] | - | Embedded engine versions to reject. A file whose embedded engine matches a listed version falls back to the bundled engine. |
The player emits an engine:source event on each resolution so you can see which engine ran:
engine.on('engine:source', ({ source, version, reason }) => {
// source: 'embedded' | 'bundled'
// version: the embedded engine's version when source === 'embedded', else null
// reason: 'preferred' | 'no-embedded-atom' | 'verification-failed' | 'sha256-mismatch'
// | 'below-floor' | 'revoked' | 'host-forced-bundled' | 'abi-unsupported'
// | 'decompression-failed'
})Plugin Security
Control network access, sandbox level, and signer requirements per plugin or group of plugins using wildcard patterns.
| Prop | Type | Default | Description |
|---|---|---|---|
pluginSecurity | Record<string, PluginSecurityRule> | - | Plugin security rules keyed by wildcard pattern. Patterns match plugin namespace:identifier format. Controls network access, sandbox level, and signer requirements per plugin or group of plugins. If set but no "*" key is provided, the implicit default is "none" (block all). If not set, every plugin runs at the "connected" sandbox level — isolated from the host page, with no same-origin access — and its mp4e.fetch reaches only the domains its manifest declares (permissions.network.domains); onNetworkGate decides any other domain, and without it the request is denied. Requests the iframe makes itself are not restricted by default. Set trustContent to opt in to the "trusted" level (and unrestricted mp4e.fetch). |
networkGateTimeoutMs | number | 5000 | How long (in milliseconds) to wait for the host to resolve a network gate request before applying the timeout policy. |
networkGateTimeoutPolicy | 'allow' | 'deny' | 'deny' | What happens when the network gate timeout expires. "allow" permits the request; "deny" blocks it. |
Trust & Signing
Shortcuts for self-hosted deployments and plugin signature verification.
| Prop | Type | Default | Description |
|---|---|---|---|
trustContent | boolean | false | Explicit opt-in to the "trusted" sandbox level. When true, every plugin receives allow-same-origin (full access to the host page and to other plugins) regardless of other pluginSecurity rules. Plugins are isolated unless you set this. Use only for self-hosted deployments where you control all content. |
trustedSigners | Record<string, string | true> | - | Trusted signers for plugin signature verification. Keys are signer names, values are base64-encoded Ed25519 public keys. The special value true for the key "mp4e" uses the built-in MP4E public key. While you trust at least one signer, a plugin whose signature does not verify (tampered content, or a signer you do not trust) runs at the "contained" level with no network access, whatever rule it matches. |
Remote Control Navigation
Every interactive object, zone and overlay can be reached with the arrow keys, OK and Back, so a D-pad remote (a TV, a set-top box) or a keyboard plays an interactive video without a pointer.
| Prop | Type | Default | Description |
|---|---|---|---|
remoteNavigation | 'on' | 'focused' | 'off' | 'focused' | Whether a remote control or keyboard can move around the video. 'on': the arrow keys, OK (Enter) and Back navigate wherever focus is on the page — for a TV app whose page is the player. 'focused': they navigate only while the player has keyboard focus, so the rest of your page keeps its keys; the player becomes a tab stop, and a viewer using a mouse or touch sees no change. 'off': never; the player is not a tab stop and plugin frames keep the browser's own behavior. Set it when the player is created. |
remoteHint | boolean | true | With remoteNavigation 'on': show "▲ Interact" in a bottom corner for about three seconds when something interactive first appears while the viewer is only watching, or when the video itself stops and waits with something to reach. Set false to hide it. It never shows with 'focused' or 'off'. |
What the viewer gets:
- Left and Right go to what is on screen on that side. With nothing on screen they go to the controls, where they move along the seek line; with no controls plugin they seek 10 seconds, as Fast Forward and Rewind always do. OK plays and pauses. The seek and the toggle are the ordinary actions
seekRelativeandtogglePlayback, so creator restrictions, yoursandboxandgatedsettings and playback paths apply to them.restrictions.actions.seekRelative: falseblocks those seeks;restrictions.actions.seek: falsedoes not. On a video withrestrictions.viewerSeeking: falsethey do not seek. - Up starts browsing and the video keeps playing: focus lands on what is holding the video if anything is, else on the overlay nearest the middle of the frame, else a ring appears on the interactive thing nearest the middle. Arrows move the ring; at an edge with nothing beyond it the ring stays. It follows an object that moves, and clears after ten seconds without a key while the video plays; on a paused video it stays.
- OK on the ring is a click, so authored tooltips, cards and rules work unchanged. A card that opens takes the focus.
- With
on, an overlay that stops the video takes the focus by itself when the viewer is not already on something: one that paused the video, or one whose own events play it again, like a quiz that a scene pauses for. - Down from the lowest target (or from watching) reaches the player controls, when the video uses the MP4E Controls plugin.
- A remote's media keys work from anywhere in the player, also inside a plugin's frame or with a card open: Play and Pause do what they say, Fast-forward and Rewind seek 10 seconds, and Stop leaves the video like Back with nothing open (your page gets
remote:back). They run as the ordinary actionsplay,pauseandseekRelative, so the same restrictions apply. A browser's combined play/pause key toggles. Colour and number keys are left to you. - An arrow stops on a text field without opening a TV's on-screen keyboard: OK or a typed character starts editing, and Back leaves editing. A keyboard viewer types at once, and Tab and clicks work as ever.
- The player's own alert, confirm and prompt keep the arrows and OK, Back closes them, and media keys wait.
- In an ad break the arrows reach the ad's controls and nothing seeks, and Skip can be reached only once the ad allows it. On an ad that holds on its last frame, its card takes the focus with
on, Back is Continue to video and Play does not start the ad again; Stop still reaches your page asremote:back. - Key bindings that the creator or you declare (
inputBindings) run first and keep their keys.
Back always gets out, one step at a time: it closes the open card, modal or panel (and counts as a click away from it, so authored click-away rules run), then clears the ring, and only then reaches your page as the remote:back event. Your page decides what that means — return to a menu, leave the screen.
// A stable object. A file can carry an older engine of its own, which plays
// without remote navigation: a page that needs it runs the bundled one.
const PLAYER_CONFIG = { remoteNavigation: 'on', engineSource: 'bundled' } as const;
<MP4EPlayer
src="/video.mp4"
autoplay
config={PLAYER_CONFIG}
onEvent={(event) => {
if (event === 'remote:back') showTheMenu();
}}
/>'focused', navigation starts when the player has focus: the viewer tabs to it, or your page focuses it. A click in the player does not turn it on, and a page's own key handling is untouched while focus is elsewhere. A TV page, where nothing else takes keys, uses 'on'.A file that carries an older embedded engine plays normally but without remote navigation, and without remote:back. A page that depends on them sets engineSource: 'bundled'.
Keys your page keeps. In every remoteNavigation mode, the player (navigation, key bindings and the input:keydown event) ignores:
- a key typed in a text field, a select or an editable region;
- a key pressed inside an element with
aria-modal="true"that does not contain the player. A modal that holds the player, and the player's own dialogs, keep their keys; - a key event your page has already handled with
preventDefault()before it reaches the player.
So mark your page's modals aria-modal="true", and call preventDefault() on a key your page handles itself. stopPropagation() in a React handler is not enough: React and the player both listen on document. A listener your page adds on document, or on window without capture, after the player starts runs after the player, so its preventDefault() comes too late.
Playback Path
Play only the scenes of one scene group, as a single continuous timeline. See setPlaybackPath on the Player Methods page.
| Prop | Type | Default | Description |
|---|---|---|---|
playbackPath | string | - | Force a playback path — the scene group id to play. Applied when set or changed (and on every metadata load); removing it from the config clears the path. A config update that keeps the same value leaves a plugin-chosen path in place; set lockPlaybackPath to keep plugins from changing it at all. |
lockPlaybackPath | boolean | false | Only the host can change the playback path. Plugin and rule calls to setPlaybackPath/clearPlaybackPath are refused with error code "playbackPath.locked"; host dispatch still works. |
Intelligence
Plugins can read an analysed video's Intelligence — chapters, key moments, things, people, the transcript — with mp4e.getIntelligence() (see Intelligence in the plugin API). What a plugin receives is what its manifest requests, the creator granted and you allow. Set this with the initial config, before plugins load.
| Prop | Type | Default | Description |
|---|---|---|---|
permissions.intelligence | string[] | no limit | The Intelligence scopes plugins may read on your site: summary, chapters, moments, questions, things, scenes, people, transcript. An allow-list that only narrows — a plugin still gets a scope only when its manifest requests it and the creator granted it. [] lets no plugin read any. A scope you leave out is reported to the plugin as withheld with reason "host". A value that is not a list lets no plugin read any scope. |
permissions.intelligence applies to every plugin, and the creator's per-plugin grants keep plugins apart because plugins are isolated from the host page and from each other by default. They stop doing so for plugins you raise to the trusted level — with trustContent or a pluginSecurity rule — since trusted plugins can reach each other's windows.<MP4EPlayer
src="/video.mp4"
config={{
permissions: { intelligence: ['chapters', 'moments'] },
}}
/>Ad Breaks
interstitials is your policy for ad breaks (pre-, mid- and post-rolls) — whether they run at all, who may request one (by default only your page; plugins you list in allowPlugins; the video's rules with allowRules), how many, how long, how far apart, which placements and from which origins, how long a break may wait on the ad's last frame (maxHoldSeconds), and what the ad itself may do (secondary: which plugins it may run, its gated actions). A wrong value restricts, never widens. Every key is on Ads in Video.
<MP4EPlayer
src="/video.mp4"
config={{
interstitials: { allowPlugins: ['mp4e:linear-ads'], maxPodSeconds: 60, maxBreaksPerHour: 6 },
}}
/>Keeping State
Where what a viewer did is kept for their next visit. See Keeping State Between Visits.
| Prop | Type | Default | Description |
|---|---|---|---|
persistence.key | string | - | The name the viewer's saved state is kept under. Give your own content id (a course lesson, a product page) when you have one: it replaces the id the video carries. Without it the video's own id is used, and a video with neither keeps nothing past the page. |
persistence.store | 'browser' | 'host' | 'none' | 'browser' | Where it is kept. browser: this browser's storage (localStorage, under mp4e:state:<key>). host: you keep it, through the initialState and onStateSave props. none: nothing is kept past the page. Any other value keeps nothing. |
Action Gating
Action gating lets the host intercept specific action types before they execute. This is useful for confirming navigation, preventing unwanted URL opens, or logging action execution. The flow is:
- A rule or plugin triggers a gated action (e.g.,
openUrl) - The engine pauses execution and invokes
onActionGate(action, resolve) - The host inspects the action and calls
resolve(true)to allow orresolve(false)to deny - If the host does not respond within
gateTimeoutMs, thegateTimeoutPolicyapplies
import { MP4EPlayer } from '@mp4e/react';
import '@mp4e/react/styles.css';
function SecurePlayer() {
return (
<MP4EPlayer
src="/video.mp4"
config={{
gated: ['openUrl', 'navigate'],
gateTimeoutMs: 10000,
gateTimeoutPolicy: 'deny',
}}
onActionGate={(action, resolve) => {
if (action.type === 'openUrl') {
// Show a confirmation dialog before opening external URLs
const approved = window.confirm(
`This video wants to open: ${action.params.url}\nAllow?`
);
resolve(approved);
} else if (action.type === 'navigate') {
// Always allow in-app navigation
resolve(true);
} else {
// Deny unknown gated actions
resolve(false);
}
}}
/>
);
}resolve(), the action is automatically denied (or allowed) after gateTimeoutMs based on the gateTimeoutPolicy. The default policy is "deny" (fail-closed).Leaving the Page
onOpenUrlGate is asked before a URL leaves the player: an openUrl or navigate action, a plugin's mp4e.openUrl among them. Without it URLs open as they always do. Use it on a page a URL would replace with no way back, such as a TV page. No answer within networkGateTimeoutMs (5 seconds by default) is a no.
A plugin can ask first, with mp4e.canOpenUrl, and show nothing when the answer is no: Ad controls does this for Learn more. That question reaches the same callback with purpose: 'offer'. So if you ask the viewer before a link opens, answer yes to 'offer' and ask on 'open'. A request from inside an ad break carries interstitial.
<MP4EPlayer
src={videoUrl}
config={{ remoteNavigation: 'on' }}
onOpenUrlGate={(request, resolve) => resolve(false)}
/>Network Gating
When a plugin uses mp4e.fetch() to request a domain not in its allowed list, the onNetworkGate callback fires. This gives the host final say over which external requests plugins can make. With no pluginSecurity, a plugin's allowed list is the domains its manifest declares (permissions.network.domains); with pluginSecurity, it is what the matching rule's network allows. Without an onNetworkGate callback, a request outside the list is denied.
The request's pluginId names the plugin frame that sent it: a service plugin's key in the video's plugins, or an overlay's plugin-<overlayId> — not the plugin's definition (namespace:identifier). A request from a plugin inside an ad break also carries interstitial (see What an ad may do).
<MP4EPlayer
src="/video.mp4"
config={{
networkGateTimeoutMs: 3000,
networkGateTimeoutPolicy: 'deny',
}}
onNetworkGate={(request, resolve) => {
// Only allow requests to your own domains
const allowed = ['api.mysite.com', 'cdn.mysite.com'];
const url = new URL(request.url);
console.log(
`Plugin ${request.pluginId} requesting ${request.method} ${request.url}`
);
resolve(allowed.includes(url.hostname));
}}
/>The callback receives the requesting plugin's ID, the full URL, and the HTTP method. A request from a plugin inside an ad break also carries interstitial: { breakId, advertiser, placement } (see What an ad may do). Call resolve(true) to allow or resolve(false) to block the request. If the host does not respond within networkGateTimeoutMs, the networkGateTimeoutPolicy applies.
Plugin Security Rules
The pluginSecurity config field maps wildcard patterns to security rules. Patterns are matched against the namespace:identifier of each plugin.
| Pattern | Matches | Example |
|---|---|---|
'*' | All plugins (global default) | Baseline security for every plugin |
'mp4e:*' | All plugins in the mp4e namespace | Official MP4E plugins |
'stripe:checkout' | Exact plugin match | Specific plugin elevated access |
'!badguy:*' | Deny rule (overrides positive matches at equal or lower specificity) | Block an entire namespace |
pluginSecurity, plugins run at the connected level: isolated from the host page and from each other, with the bridge's storage and fetch available. A plugin's mp4e.fetch reaches only the domains its manifest declares in permissions.network.domains; any other domain goes to onNetworkGate, and without it the request is denied. Requests the iframe makes itself are unrestricted by default. A rule's sandbox picks a different level for the plugins it matches; set trustContent to raise every plugin to trusted.pluginSecurity is set but does not include a '*' key, the implicit default is "none" (all plugins blocked). Always include a '*' entry as your baseline.PluginSecurityRule Type
interface PluginSecurityRule {
/**
* Network access policy:
* - 'none': Block all network access
* - 'manifest': Allow only domains declared in plugin manifest
* - 'any': Unrestricted (dangerous, explicit opt-in only)
* - string[]: Explicit domain allowlist (replaces manifest)
* Applies to mp4e.fetch and, through the plugin frame's Content
* Security Policy, to the plugin's own requests: fetch, XMLHttpRequest
* and WebSocket connections, images and form posts may reach only the
* listed domains (none for 'none'). Under 'none', 'manifest' or a domain
* list, scripts and styles must be inline in the plugin — external
* scripts and stylesheets do not load, even from a listed domain.
*/
network?: 'none' | 'manifest' | 'any' | string[];
/**
* Sandbox level controlling iframe capabilities:
* - 'contained': allow-scripts, allow-forms only (NO same-origin)
* - 'connected': the default when no pluginSecurity is set (the iframe
* is isolated; use mp4e.storage / mp4e.fetch)
* - 'trusted': + allow-same-origin (full host page access)
*/
sandbox?: 'contained' | 'connected' | 'trusted';
/**
* Required signer name. The rule applies only to a plugin signed by this
* signer (checked against trustedSigners). An unsigned plugin, a plugin
* signed by a different trusted signer, or a host with no trustedSigners
* gets the 'contained' level and no network access instead.
*/
signer?: string;
}Full Example
<MP4EPlayer
src="/video.mp4"
config={{
pluginSecurity: {
// Global default: contained sandbox, no network
'*': {
sandbox: 'contained',
network: 'none',
},
// Official MP4E plugins: connected sandbox, manifest-declared domains
'mp4e:*': {
sandbox: 'connected',
network: 'manifest',
signer: 'mp4e',
},
// Stripe plugins: connected sandbox, explicit domain allowlist
'stripe:*': {
sandbox: 'connected',
network: ['js.stripe.com', 'api.stripe.com'],
},
// Specific trusted plugin: full access
'stripe:checkout': {
sandbox: 'trusted',
network: 'any',
},
// Block a known-bad namespace entirely
'!badguy:*': {
sandbox: 'contained',
network: 'none',
},
},
}}
/>Content Restrictions
Content restrictions are creator-declared and embedded in metadata.settings.restrictions. They are the first tier of the permission model and are enforced by the engine even when no host config is provided. Think of them like SCORM sequencing rules.
MP4ERestrictions
| Prop | Type | Default | Description |
|---|---|---|---|
actions | Record<string, boolean> | - | Action types the creator wants blocked. Same shape as config.sandbox.actions. Blocked actions are silently dropped by the engine. |
sequential | boolean | false | Force linear playback. When true, the viewer cannot seek forward past the furthest-watched point. Similar to SCORM's forwardOnly mode. |
viewerSeeking | boolean | true | Whether viewers may seek. When false, the player refuses every seek the viewer asks for: the seek bar, skip buttons and double-tap skip, keyboard shortcuts, a TV remote's seek, any plugin's seekToTime, and a seek made on the video element itself (for example from the browser's own controls), which it puts back. The controls leave out the seek bar, the time and the skip buttons. The video's own seeks (rules, goToScene, scene loops, playback paths) and your seek() calls still work. |
// Creator embeds restrictions in the video metadata
// These are enforced by the engine regardless of host config
{
"settings": {
"restrictions": {
"sequential": true,
"actions": {
"download": false,
"openUrl": false
}
}
}
}sequential is enabled, the engine tracks the furthest-watched point and prevents seeking beyond it. This is commonly used for e-learning and compliance training videos where linear completion is required.No Viewer Seeking
A branching show, a quiz or a course that must be watched through can set viewerSeeking: false. The player then refuses every seek the viewer asks for: the seek bar, the skip buttons and double-tap skip, keyboard shortcuts, a TV remote's seek, any plugin's seekToTime, and a seek made on the video element itself (the browser's own controls, your nativeControls), which it puts back where the video was. Play, pause, volume, settings and full screen keep working, and the controls leave out the seek bar, the time and the skip buttons.
What still moves the video: the video's own rules and scene jumps (seek actions in rules, goToScene, scene loops, playback paths, the return from an ad break) and your page's seek() and seekToFrame(). A refused request is reported as action:blocked with reason viewerSeeking; a seek of the element that was put back is reported as playback:restricted with the same reason, the time asked for (requestedTime) and the time the video stayed at (currentTime).
This is not actions: { seek: false }, which blocks the seek action for everyone, the video's own rules included.
// A branching show: viewers can't seek, the show's own jumps still work
{
"settings": {
"restrictions": { "viewerSeeking": false }
}
}
// Your page can still move the video, and hears what was refused
playerRef.current?.seek(0); // allowed: the host's seek
<MP4EPlayer
src="/show.mp4"
onEvent={(event, data) => {
if (event === 'action:blocked' && data.reason === 'viewerSeeking') {
// the seek bar, a key, a remote or a plugin asked to seek
}
if (event === 'playback:restricted' && data.reason === 'viewerSeeking') {
// the video element seeked by itself (e.g. the browser's controls)
// and was put back at data.currentTime
}
}}
/>One scene at a time
A creator can also close single scenes to the viewer's own jumps, with access.viewerSeek on the scene:
always(the default): the viewer may jump into the scene.reached: only once they have played into it. A course: go back over what you saw, no skipping ahead.never: only the video sends the viewer there. A result that has to be earned.
Playing into the scene, the video's own rules and your own calls are never restricted. A refused jump raises action:blocked with the reason sceneAccess and targetScene; a seek made on the video element itself is put back with playback:restricted. scenes:locked tells you which stretches are closed ({ ranges: [[from, to]] }, in seconds), so your own seek bar can show them.
{
"id": "scene_jackpot",
"name": "Jackpot",
"startFrame": 2112,
"endFrame": 2303,
"access": { "viewerSeek": "never" }
}Keeping State Between Visits
A video can remember what a viewer did and give it back on their next visit: a quiz score, a cart, the choices made in a story. The creator chooses what is kept — each variable marked “Remember between visits”, and the state a plugin's author keeps (a cart's items) — and, with the video's Resume setting (settings.resume: off, the default, ask or always), where the viewer was and the scenes they reached. You choose the name it is kept under and where it is kept.
The key
Saved state is kept under one key, chosen in this order:
- your
config.persistence.key, when you give one; - else the id the video carries (
documentId: the Studio gives every project one and keeps it through edits and exports; a copy of a project gets a new one); - else nothing: the video keeps nothing past the page.
Plugin storage (mp4e.storage) is kept under the same key, as mp4e:plugin:<key>:<instance id>:<name>, so two videos whose plugins share an id do not share what they store.
Where it is kept
browser(the default): this browser's storage, undermp4e:state:<key>.host: you keep it. The player callsonStateSave(snapshot)with each new snapshot; keep the latest one (on your server, for a signed-in viewer) and pass it back asinitialStatenext time. A snapshot whosekeyis not this video's key is not used.none: nothing is kept past the page.
The viewer's choice wins: when they ask to limit storage (the limitStorage viewer preference), nothing lasts past the session — the browser store keeps it only until the tab closes (sessionStorage) and onStateSave is not called. A video playing as an ad break never keeps anything.
A snapshot is saved after a remembered value changes (at most once a second), on pause, a seek and a change of scene, every 5 seconds while playing when the viewer's place is kept, and once more when the page is hidden. Each save is reported as state:save (see Player Events), except the last one when the page is hidden, which reaches storage and onStateSave without an event. A saved value that no longer fits its variable (the creator changed it since) is left out; the rest come back.
<MP4EPlayer
src="/lesson-12.mp4"
config={{ persistence: { key: 'course-7/lesson-12', store: 'host' } }}
initialState={savedSnapshot} // what onStateSave gave you last time, or null
onStateSave={(snapshot) => {
fetch('/api/progress/lesson-12', { method: 'PUT', body: JSON.stringify(snapshot) });
}}
/>persistence.key when it matters which content the state belongs to.Resume
With Resume on, the viewer's place comes back too. always starts the video there. ask asks first: “Continue from 4:12?” with Continue and Start over. Continue goes back to that place. Start over puts every remembered value back to its starting value, forgets the scenes reached, and forgets the saved snapshot (state:clear); the video plays from where it is.
The viewer's place is not taken back (the remembered values still are) on live video; during an ad break; when the video does not let viewers seek (viewerSeeking: false); when the video cannot seek or your sandbox blocks seek; outside the playback path that is playing; inside a scene the viewer may not jump into; under 1 second; or within 5 seconds of the end. Going back is an ordinary seek: when you list seek in gated, onActionGate is asked first, and it is reported as after:seek.
To ask in your own way with @mp4e/player, listen to dialog:show on the engine: the player then draws none of its dialogs and hands each to you. The resume question arrives as a confirm with config.resume.position (seconds); call its resolve(true) for Continue or resolve(false) for Start over, and the player gives the engine the answer (answerResume). The question is also announced as resume:offer.
engine.on('dialog:show', (dialog) => {
if (dialog.config?.resume) {
showMyResumeCard(dialog.config.resume.position, (resume: boolean) => dialog.resolve(resume));
return;
}
showMyDialog(dialog); // every other dialog is yours to draw too
});onReady) still see the starting values; scenes, plugins, templates and every later rule see the values that came back.Security Violations
The onSecurityViolation callback fires when a plugin attempts a blocked network request (CSP violation). Use it for monitoring and alerting.
<MP4EPlayer
src="/video.mp4"
onSecurityViolation={(violation) => {
console.error(
`Security violation by plugin ${violation.pluginId}:\n` +
` Blocked URI: ${violation.blockedURI}\n` +
` Violated directive: ${violation.violatedDirective}`
);
// Report to your monitoring service
analytics.track('security_violation', {
pluginId: violation.pluginId,
blockedURI: violation.blockedURI,
directive: violation.violatedDirective,
});
}}
/>| Field | Type | Description |
|---|---|---|
pluginId | string | The ID of the plugin that triggered the violation. |
blockedURI | string | The URI that was blocked by the Content Security Policy. |
violatedDirective | string | The CSP directive that was violated (e.g., "connect-src", "script-src"). |
Interactive Tool
MP4EConfig object. Select action types to sandbox, choose plugins to disable, configure gating policies, and set up plugin security rules -- then copy the generated config directly into your code.Full Production Example
Putting it all together -- a production-ready player with sandbox rules, action gating, plugin security, and violation monitoring:
import { MP4EPlayer } from '@mp4e/react';
import '@mp4e/react/styles.css';
function ProductionPlayer({ videoUrl }: { videoUrl: string }) {
return (
<MP4EPlayer
src={videoUrl}
config={{
// Block dangerous actions entirely
sandbox: {
actions: {
download: false,
openUrl: false,
},
},
// Require approval for navigation
gated: ['navigate', 'goToScene'],
gateTimeoutMs: 8000,
gateTimeoutPolicy: 'deny',
// Disable specific creator content
disabled: {
layers: ['debug-layer'],
actionTypes: ['console'],
},
// Plugin security per namespace
pluginSecurity: {
'*': { sandbox: 'contained', network: 'none' },
'mp4e:*': { sandbox: 'connected', network: 'manifest' },
'stripe:checkout': { sandbox: 'trusted', network: 'any' },
},
// Trust official MP4E signatures
trustedSigners: { mp4e: true },
}}
// Gate callbacks
onActionGate={(action, resolve) => {
resolve(window.confirm(`Allow action: ${action.type}?`));
}}
onNetworkGate={(req, resolve) => {
const trusted = ['api.mysite.com', 'cdn.mysite.com'];
resolve(trusted.includes(new URL(req.url).hostname));
}}
onSecurityViolation={(v) => {
console.error('Security violation:', v);
}}
/>
);
}