Building widgets (Dima SDK)
Developer reference for building Overlay Studio custom widgets with a manifest, editable fields, and Dima SDK v1.
This reference is for developers building custom widgets for Overlay Studio. Each widget is a lightweight HTML, CSS, and JavaScript package that executes inside a sandboxed iframe. Native widgets talk directly to the Dima SDK, while StreamElements packages run on top of a compatibility layer built over the same SDK.
Looking for the streamer setup guide instead? See Custom widgets.
You can also code directly inside Overlay Studio using New widget and the Dima SDK starter—see Write code in Studio.
TypeScript definitions for the SDK ship inside Download for your editor.
Package files
Section titled “Package files”A widget package can include the following files:
| File | Purpose |
|---|---|
widget.json | Optional manifest for native Dima widgets; required to select the native Dima engine and declare live data categories. StreamElements packages without one are inferred from their code. |
widget.ini | StreamElements mapping from package sections to filenames. |
html.txt | HTML markup injected into the iframe body. |
css.txt | Stylesheet injected into the iframe. |
js.txt | Classic JavaScript script executed after the HTML is in place. |
fields.txt | JSON object describing user-editable settings. |
data.txt | JSON object holding saved setting values. |
StreamElements packages use widget.ini to locate the HTML, CSS, JavaScript, fields, and data files. Native Dima widgets use widget.json alongside the same content files and don’t need widget.ini. On import, Studio keeps the original fields and data text intact so exports stay lossless.
widget.json manifest
Section titled “widget.json manifest”widget.json is a JSON object supporting these properties:
| Field | Required | Meaning |
|---|---|---|
engine | No | "dima" for native Dima SDK widgets, or "streamelements" to load the StreamElements compatibility layer. Defaults to "dima" whenever a manifest is present; packages without a manifest default to StreamElements. |
api | No | Dima SDK major version. Defaults to 1; unsupported versions are rejected. |
uses | No | Array of live data categories the widget needs: chat, alerts, storage, counters, session, signals, polls, goals, tts, triggers, rewards, pets, duels, roulette, dimafx, hypetrain, and/or ads. Defaults to an empty array. Unknown entries are reported and ignored. |
name | No | Display name shown in Studio. |
author | No | Author or creator name. |
version | No | Package version string. |
description | No | Brief summary of what the widget does. |
signals | No | Optional signal definitions (up to 30) used to generate ready-made commands in Studio. Each takes a lowercase name, optional description (up to 200 characters), and optional values examples (up to 30 entries, each up to 60 characters). Invalid entries are skipped with the import note signal declaration skipped. |
{ "engine": "dima", "api": 1, "name": "Pastel chat", "author": "Ana", "version": "1.2.0", "description": "Chat with pastel bubbles", "uses": ["chat", "alerts", "storage", "counters", "session", "signals", "polls", "goals", "tts", "triggers", "rewards"], "signals": [{ "name": "feed", "description": "Feed the pet", "values": ["pizza", "cake"] }]}Request only the data categories your widget genuinely uses:
chatenables chat messages, message deletions, and chat clears.alertsenables follow, subscription, gift, Bits, raid, and tip alert categories (real tip events aren’t available yet).storageenables persistent key/value storage,countersenables reading command counts,sessionenables recent events and totals, andsignalslets chat commands trigger the widget.polls,goals,hypetrain, andadsprovide their respective live state snapshots.tts,triggers,rewards,pets,duels,roulette, anddimafxemit those bot events.
Studio presents the uses list to the channel owner on import, and published widgets only receive categories they declared. Editor button tests always work regardless of uses.
Editable settings
Section titled “Editable settings”fields.txt is a JSON object keyed by setting name. Each field definition accepts type, label, value (default), group, and type-specific options such as min, max, step, and options. Settings sharing a group appear together in a collapsible section, while ungrouped fields land under General. Hidden fields remain readable from your script. Studio’s search filters by field labels. Each overlay layer stores only its overrides; resetting a setting clears that override.
Supported field types:
text,textarea,number, andslider(optionalmin,max,step)checkboxcolorpickerdropdown(optionsmaps option values to display labels)googleFontimage-input,video-input, andsound-input(addmultiple: truefor a list of URLs)button(fires an editor-onlybuttonevent to your widget)hidden(omitted from the editor UI)
For example:
{ "accent": { "type": "colorpicker", "label": "Accent", "value": "#7c3aed", "group": "Look" }, "limit": { "type": "number", "label": "Messages on screen", "value": 6, "min": 1, "max": 30, "group": "Chat" }, "hideCommands": { "type": "checkbox", "label": "Hide !commands", "value": true, "group": "Chat" }}Field values resolve in order: field default → package data.txt → per-layer override. You can inject values into HTML and CSS with {key} or {{key}} (for example, {{countLabel}}). Only known keys are replaced; arrays join with commas and null becomes an empty string. Native Dima widgets only run template substitution in HTML and CSS—read current values from Dima.fields in JavaScript. StreamElements widgets also run substitution in JavaScript for compatibility. On import, Studio guards closing </script and </style sequences inside substituted values.
Dima SDK v1
Section titled “Dima SDK v1”Inside the widget iframe, the SDK is exposed globally as Dima.
const ctx = await Dima.ready();// ctx: { widget, channel, fields, mode, muted, session, goalSource }Dima.fields; // current settingsconst unsubscribe = Dima.on('chat', message => { /* ... */ });Dima.off('chat', handler); // or call the function returned by Dima.onDima.storage.get('key'); // Promise resolving to a JSON value or nullDima.storage.set('key', { seen: true }); // PromiseDima.counters.get('!deaths'); // Promise<number>Dima.html(message); // escaped text plus safe Twitch emote imagesDima.escape(viewerText); // escaped stringDima.log('loaded'); // appears in Studio's Widget logawait Dima.setField('accent', '#ff66aa'); // editor onlyNative Dima widgets use Dima.storage.get/set, the storage event, and "storage" in widget.json uses, while StreamElements widgets keep SE_API.store and kvstore:update.
Dima.setField(key, value, reload = true)is strictly for editor-only helpers: it updates a field programmatically, validates it against the field schema, and rejects in live mode.Dima.done()is a no-op in v1.- Storage namespaces are isolated per widget ID for native Dima widgets, whereas StreamElements widgets share the channel-wide
senamespace (matching StreamElements’ shared kvstore). Storage update events carryDimaStorageUpdate { key, value, namespace }, and a widget only receives updates for its own namespace (its widget ID for native Dima, orsefor StreamElements widgets).
Command signals
Section titled “Command signals”Add "signals" to uses to listen for chat-command signals. You can also list up to 30 signal definitions in widget.json so Studio can scaffold ready-made commands: omitting values generates a command with no argument; single-word examples pass the viewer’s first word (&p1); any example containing spaces passes all text after the command (&t). Names must use lowercase letters, digits, and _ (up to 40 characters); invalid definitions are skipped with signal declaration skipped.
{ "uses": ["signals"], "signals": [{ "name": "feed", "description": "Feed the pet", "values": ["pizza", "cake"] }]}Listen for all signals or subscribe to a specific signal name. Because signal values originate from viewer input, always render them with textContent or Dima.escape(), never innerHTML.
Dima.on('signal', signal => { /* handle every signal */ });Dima.on('signal:feed', signal => { document.querySelector('.pet-status').textContent = `Eating ${signal.value || 'snack'}`;});A DimaSignal payload includes:
id,name,value(text following the signal name, or''),json(parsed only whenvalueis a JSON number, boolean, array, or object; otherwisenull),args(valuesplit on spaces), andat(milliseconds).user:{ id, login, name }plus verified Twitch badge roles (broadcaster,moderator,vip,subscriber), ornullif unknown.source:{ kind, name }, wherekindiscommand,keyword,event, orstudio.target: the layer name for targeted signals, ornullotherwise.
In StreamElements compatibility mode, the exact same payload arrives via onEventReceived with listener: 'dima:signal' (obj.detail.event.name, .value, .user, etc.), letting a single codebase work on both engines.
Events
Section titled “Events”Attach listeners with Dima.on(type, handler), which returns an unsubscribe callback; you can also remove listeners with Dima.off(type, handler).
| Event | data shape | Requires uses |
|---|---|---|
chat | DimaChat (shape below) | chat |
chat.delete | { messageId: string, userId: string | null } | chat |
chat.clear | { userId: string | null }; null means the whole chat | chat |
alert | DimaAlert (shape below) | alerts |
button | { field: string, value: unknown } | Editor only; always available in preview |
fields | The current settings object | Editor only |
storage | DimaStorageUpdate { key: string, value: unknown, namespace: string } after a storage write | storage |
session | { data: Record<string, unknown>, recents: unknown[] } | session |
signal / signal:<name> | DimaSignal | signals |
state | DimaState ({ name, value }) | polls, goals, hypetrain, or ads, according to name |
tts | DimaTts | tts |
trigger | DimaTrigger | triggers |
reward | DimaReward | rewards |
pet | DimaPet | pets |
duel | DimaDuel | duels |
roulette | DimaRoulette | roulette |
dimafx | DimaDimafx | dimafx |
Live state
Section titled “Live state”Call Dima.state(name, handler) to subscribe to the latest known snapshot and future updates for polls, goals, hype trains, or ad breaks. Whenever an OBS source connects or reconnects, the current snapshot is delivered again. Your handler fires once a value becomes known and on every subsequent change—if no value is known yet, it stays silent (unknown is distinct from an empty poll or goals list). The returned function unsubscribes. To watch all state domains at once, use Dima.on('state', ({ name, value }) => …).
const stopPolls = Dima.state('polls', ({ poll, prediction }) => { document.querySelector('#poll-title').textContent = poll?.title ?? 'No poll yet';});Dima.state('goals', goals => { document.querySelector('#goal-count').textContent = String(goals.length);});// Later: stopPolls();hypetrain(requires"hypetrain"inuses): returns aDimaHypeTrainornull. Represents the active train or one that just finished—an ended train remains visible until its cooldown expires (at most two hours), then flips tonull. If DomDimaBot misses an end event, it queries Twitch and clears stale active state when Twitch reports no train. Fields:id,phase(activeorended),level,total(Twitch point units),progressandgoal(points toward and needed for the next level; bothnullonce ended),topContributions,allTimeHigh({ level, total }ornull),type(regular,golden_kappa, ortreasure),shared,sharedParticipants(channels in a shared train),startedAt,expiresAt(when the train ends without new contributions;nullonce ended),endedAt, andcooldownEndsAt. EachDimaHypeContributionhasuser(id,login,name),type(bits,subscription, orother), andtotal(points); Twitch publishes top contributors publicly. All timestamps are in milliseconds.ads(requires"ads"inuses): returnsDimaAds, withactive(nullorDimaAdBreakcontainingstartedAt,endsAt,durationin seconds, andautomaticfor schedule-triggered breaks) andschedule(DimaAdScheduleornullwhen unknown).DimaAdScheduleexposesnextAt(alsonullwhen no break is scheduled or the channel is offline),duration(seconds),lastAt,snoozes,snoozeRefreshAt, andprerollFreeUntil—any schedule field can benullwhen Twitch omits it. All timestamps are milliseconds and durations are seconds. Because Twitch has no schedule-change event, DomDimaBot polls the schedule roughly once a minute while an OBS source with an ads widget is connected. Who started an ad is never exposed. Streamers who logged in before the ad-schedule scope was added may need to sign in again beforeschedulestops returningnull.polls(requires"polls"inuses): returnsDimaPolls({ poll, prediction }), where each property isnullor aDimaPoll. ADimaPollincludeskind(pollorprediction),id,title,phase(active,locked,completed,archived,terminated,resolved, orcanceled),choices,startedAt,deadline,endedAt,winnerId, andrevision. Each choice carriesid,title,votes,users, andpoints, plus optionalchannelPointsVotesandcolor. Data contains aggregate totals only and never identifies voters. Live poll/prediction state arrives once Twitch events are enabled via the same Polls & predictions setup shown on the Overlay tab.goals(requires"goals"inuses): returns an array ofDimaGoalentries from the layer’s selected goal source. Each entry providesid,source('dima'or'twitch'),name,metric(follows,subs,subPoints,bits,cheerers, orcurrency),mode,target,current,percent,currency(code ornull),twitchType(e.g.,follow,subscription_count,new_bit;nullfor Goals page goals),achieved(whether Twitch marked an ended Twitch goal as reached),status(scheduled,active,reached, orended),startsAt,endsAt,windowSeconds, andperiod. Twitch goals setmode: 'twitch'; monetary amounts use currency units (for example,87.5). Updates arrive within seconds of edits or progress changes and at least once per minute for time-based transitions. Goal state is read-only and never runs goal completion actions.
StreamElements-compatible widgets receive live state via onEventReceived: dima:hypetrain provides event.hypetrain (null when no train is visible), and dima:ads provides event.active and event.schedule.
Bot events
Section titled “Bot events”Most bot events are live-only—an OBS source reconnecting after a drop won’t receive events missed while offline. Roulette results are the exception: they’re backed by saved spins and can replay for up to two minutes after endsAt. Every bot event includes at (milliseconds) and test (true for Studio tests).
| Event | Data | Notes |
|---|---|---|
tts (uses: ["tts"]) | DimaTts: id, phase (start or end), text, user, reason | text is the filtered spoken string. start fires when audio begins; end fires once when playback finishes with reason set to ended, skipped, cleared, or interrupted. Both phases share id; messages that never play produce no event. |
trigger (uses: ["triggers"]) | DimaTrigger: id, triggerId, name, mediaType (audio, video, image, or unknown) | Fires when a command, channel-point redemption, or Bits rule sends a trigger alert. Does not include a media URL, and a custom-widget-only overlay observes the event without playing the media. |
reward (uses: ["rewards"]) | DimaReward: id, reward: { id, title, cost }, user, input | Fires for every channel-point redemption, even rewards with no bot action. Treat input as viewer text—always use textContent or Dima.escape(), never innerHTML. |
pet (uses: ["pets"]) | DimaPet: id, kind, phase, text, mood, result | Fires when the pet starts speaking and once when it finishes, only for spoken replies. Handle done even if no speaking arrived first. text is the pet’s line, never the viewer’s prompt. Private DomDimaBot desktop app replies are not sent to widgets. |
duel (uses: ["duels"]) | DimaDuel: id, phase, challenger, opponent, mode, winner, loser, endsAt | Names are Twitch logins. started fires when a challenge is accepted or someone challenges the streamer; ended fires once after the fight, revealing the outcome only then. |
roulette (uses: ["roulette"]) | DimaRoulette: id, rouletteId, name, phase, label, endsAt | Fires spinning, then result with the winning label when the spin finishes. Backed by saved spins so API restarts or OBS reconnects don’t lose results; sources connecting within two minutes after endsAt still receive it (check endsAt if you want to skip old spins). |
dimafx (uses: ["dimafx"]) | DimaDimafx: id, item, source, bits, credits, user, message | Fires once when a DimaFX item starts playing (requires the DimaFX overlay to be connected). Viewer identity is present only when shared with the extension. Custom TTS message is viewer input—use textContent or Dima.escape(), never innerHTML. |
Field details for the four feature events:
DimaPet:DimaPet.kindistalk,ask, ortts;phasemoves fromspeakingtodone;moodisnullwhen moods are off;resultiscompletedorstoppedondoneonly.DimaDuel:DimaDuel.phasemoves fromstartedtoended;challengerandopponentare Twitch logins;modeisoverlayorchat;winnerandloserstaynulluntilended;endsAtmay benull.DimaRoulette:DimaRoulette.phasemoves fromspinningtoresult;labelis populated onresultonly.DimaDimafx:itemis{ id, name, type };sourceisbits,credits,saved, ortest;bitsandcreditshold the paid amount ornull;useris{ id, login, name }only when the viewer shared their identity with the extension (otherwisenull);messageholds viewer text only for custom TTS items (otherwisenull).
Dima.on('tts', event => { if (event.phase === 'start') document.querySelector('#spoken').textContent = event.text;});Dima.on('trigger', event => console.log(event.name, event.mediaType));Dima.on('reward', event => { document.querySelector('#reward-input').textContent = event.input ?? '';});Dima.on('pet', event => { if (event.phase === 'speaking') document.querySelector('#pet').textContent = event.text;});Dima.on('duel', event => console.log(event.phase, event.challenger, event.opponent));Dima.on('roulette', event => { if (event.phase === 'result') document.querySelector('#winner').textContent = event.label ?? '';});Dima.on('dimafx', event => console.log(event.item.name, event.source));Full type definitions live under DimaPet, DimaDuel, DimaRoulette, and DimaDimafx. StreamElements-compatible widgets receive these same events through onEventReceived using listeners dima:pet, dima:duel, dima:roulette, and dima:dimafx (obj.detail.event). All four include at (milliseconds) and test (true for Studio tests). Pet, duel, and DimaFX events are live-only, whereas roulette results come from saved spins and can replay for up to two minutes after endsAt.
Studio state and event tests
Section titled “Studio state and event tests”Whenever any widget in an overlay declares one of these categories, Studio enables the Bot events row so you can send TTS (start, followed by end three seconds later), Trigger, Channel points, Sample poll, Sample goals, Sample hype train, Sample ad break, Pet reply, Duel, Roulette, and DimaFX purchase events to either the preview or OBS. Paired events automatically send their second phase about three seconds later, and the code editor preview exposes the same test buttons. Sample state sent to OBS stays visible for about a minute before real state returns; Studio previews initialize with your channel’s real polls, goals, hype train, and ad state.
The Replay recent chat button inside the Chat row works in the preview only. It replays the channel’s last 20 stored messages from oldest to newest as plain text (no emotes, name colors, or badge images) and may include messages deleted by moderators, so it is never sent to OBS.
Dima.ready() resolves to an object containing widget: { id, layerId, name, revision }, channel: { id, login, name }, fields, mode ("editor" or "live"), muted, session (or null), and goalSource ('dima' or 'twitch'), reflecting the layer’s selected goal source.
A chat event (DimaChat) has this shape:
{ id: string; platform: 'twitch'; at: number; user: { id: string; login: string; name: string; color: string | null; badges: Array<{ set: string; version: string; info: string; title: string; images: { '1x': string; '2x': string; '4x': string } }>; roles: { broadcaster: boolean; moderator: boolean; vip: boolean; subscriber: boolean; founder: boolean; artist: boolean; staff: boolean; partner: boolean; turbo: boolean; prime: boolean }; subMonths: number | null; }; text: string; parts: Array< | { type: 'text'; text: string } | { type: 'emote'; text: string; id: string; animated: boolean; images: { '1x': string; '2x': string; '4x': string } } | { type: 'cheer'; text: string; prefix: string; bits: number; tier: number } | { type: 'mention'; text: string; user: { id: string; login: string; name: string } } >; kind: 'text' | 'highlighted' | 'intro' | 'power-up' | 'gigantified'; action: boolean; firstMessage: boolean; bits: number; rewardId: string | null; reply: { id: string; user: { id: string; login: string; name: string }; text: string } | null; sharedChat: { channelId: string; messageId: string } | null;}An alert event (DimaAlert) has this shape:
{ id: string; type: 'follow' | 'sub' | 'resub' | 'gift' | 'bits' | 'raid' | 'tip'; at: number; test: boolean; user: { id: string; login: string; name: string } | null; amount: number; // months, gifts, Bits, raid viewers, or tip amount tier: '1000' | '2000' | '3000' | 'prime' | null; months: number | null; streak: number | null; message: string | null; recipient: { id: string; login: string; name: string } | null; currency: string | null; rule: { id: string; name: string } | null;}DimaSession.data mirrors StreamElements’ session snapshot (keys like follower-latest, subscriber-recent, cheer-session, and follower-week), while recents holds recent alert entries:
*-sessioncovers the current stream (or the past 24 hours if no stream start is recorded),*-weekcovers the past 7 days, and*-month(followers, subscribers, Bits, and raids) covers the current UTC calendar month.*-latestand*-recentare derived from the newest 500 alerts, with up to 25 entries per*-recentarray.follower-totalandsubscriber-totalmirror your dashboard totals (follows update live).cheer-totalandraid-totalcover the last 90 days (the channel event retention window), so they can drop as older events age out. Subscriber counts include each subscriber once plus gifted subs—a 5-sub community gift adds 5.
The StreamElements manual goal keys (follower-goal, subscriber-goal, cheer-goal, and tip-goal) each return { amount } based on the layer’s Goal data setting:
- For Goals page goals, each key pulls from the first active matching goal in the streamer’s list, or the first reached goal if none are active. The
amountis current progress—not the target—calculated with the counting rule chosen on the Goals page (since creation, current count, set dates, rolling window, or calendar month). Money (tip-goal) uses currency units (e.g.,12.34) and includes everything counted by that goal (Bits, subs, custom items—not just tips). - For Twitch goals, follower goals feed
follower-goal, sub goals feedsubscriber-goal(counts before points), Bits goals feedcheer-goal, andtip-goalstays 0 because Twitch has no money goals. Any unmatched key returns 0. - Updated values flow through
session(Dima) andonSessionUpdate(StreamElements), reaching OBS widgets within seconds of changes. Studio test alerts update session totals in the preview and push updated totals to OBS without touching real data; Twitch-sourced goals don’t change on test alerts because Twitch computes its own goals, though session counts still update. Tip event keys (tip-*) stay at 0 until DomDimaBot tipping launches.
Totals that cannot yet be computed default to zero. Inline HTML onerror="…" handlers in StreamElements widgets can safely reference functions defined in the widget’s script—early image errors wait until that script runs, matching StreamElements behavior.
Use Dima.html(message) to escape message text and render safe <img> elements for Twitch emotes. When building HTML strings with viewer-controlled text, escape values via Dima.escape, or prefer textContent for plain text nodes.
Complete native example
Section titled “Complete native example”Here is a compact chat widget adapted from the dima-chat sample. It declares its data needs, escapes viewer text safely, handles moderation events, and uses both storage and command counters.
widget.json:
{ "engine": "dima", "api": 1, "name": "Dima sample chat", "author": "DomDimaBot", "version": "1.0.0", "description": "A compact chat overlay", "uses": ["chat", "storage", "counters"]}fields.txt:
{ "accent": { "type": "colorpicker", "label": "Accent", "value": "#7c3aed", "group": "Look" }, "limit": { "type": "number", "label": "Messages on screen", "value": 6, "min": 1, "max": 30, "group": "Chat" }}html.txt:
<ol class="chat" aria-live="polite"></ol><footer><span class="count">0</span> alerts · <span class="deaths">0</span> deaths</footer>css.txt:
:root { --accent: {accent}; }body { margin: 0; color: white; font: 18px system-ui, sans-serif; }.chat { display: flex; flex-direction: column; gap: 6px; list-style: none; padding: 12px; }.msg { padding: 8px 12px; border-left: 4px solid var(--accent); background: #111c; }.msg img.dima-emote { height: 1.4em; vertical-align: middle; }js.txt:
const chat = document.querySelector('.chat');const count = document.querySelector('.count');const deaths = document.querySelector('.deaths');let fields = {};Dima.ready().then(async ctx => { fields = ctx.fields; count.textContent = String((await Dima.storage.get('alerts')) ?? 0); deaths.textContent = String(await Dima.counters.get('!deaths'));});Dima.on('fields', next => { fields = next; });Dima.on('chat', message => { const item = document.createElement('li'); item.className = 'msg'; item.dataset.id = message.id; item.innerHTML = '<strong>' + Dima.escape(message.user.name) + '</strong> ' + Dima.html(message); chat.append(item); while (chat.children.length > Number(fields.limit || 6)) chat.firstElementChild.remove();});Dima.on('chat.delete', ({ messageId }) => { chat.querySelector('[data-id="' + CSS.escape(messageId) + '"]')?.remove();});Dima.on('chat.clear', () => { chat.replaceChildren(); });Notice there is no widget.ini: Studio imports these native files straight into an overlay.
StreamElements compatibility
Section titled “StreamElements compatibility”Setting "engine": "streamelements" (or importing a package without widget.json) enables the compatibility layer, which bridges Dima SDK events to standard StreamElements browser events:
onWidgetLoadfires right afterDima.ready()withdetail.channel,currency,fieldData,recents,session,overlay, andemotes.onEventReceivedmaps chat tolistener: "message", single-message deletion to"delete-message", user chat clear to"delete-messages", and alerts to"follower-latest","subscriber-latest","cheer-latest","raid-latest", or"tip-latest". It also delivers"widget-button","kvstore:update","dima:signal","dima:polls"(event.poll,event.prediction),"dima:goals"(event.goals),"dima:tts","dima:trigger", and"dima:reward".onSessionUpdatefires on session changes with{ session }.
For chat messages, event.data supplies time, IRC-style tags, nick, userId, displayName, displayColor, badges, channel, text, isAction, emotes, and msgId, while event.renderedText provides escaped HTML with Twitch emotes. Alert payloads include the standard fields for each type—such as name, amount, tier, message, gifted, sender, or currency.
Available SE_API methods: store.get/set, counters.get(name), sanitize({ message }), cheerFilter(text), getOverlayStatus(), resumeQueue(), and setField(key, value, reload). sanitize returns the message unchanged, and setField works only in the editor. Key compatibility behaviors:
- Storage scope: Unlike native Dima widgets (which are scoped per widget),
SE_API.storestays channel-wide. - Alert queueing: Defining a
widgetDurationsetting queuesonEventReceivedalert events one at a time, holding each for that many seconds (up to 300) unlessSE_API.resumeQueue()advances early. Up to 50 alerts can wait; chat and other events never queue. WithoutwidgetDuration, alerts aren’t queued. - Whole-chat clear: StreamElements has no native whole-chat-clear event, so clearing the entire chat reloads StreamElements widgets fresh, whereas clearing a single user maps to
delete-messages(native Dima widgets getchat.clearwithuserId: null). - Unsupported features: No StreamElements API token, StreamElements-only APIs, or third-party emotes.
- Substitution & reload: StreamElements widgets run
{key}/{{key}}substitution across HTML, CSS, and JavaScript, and reload when editor settings change—matching native StreamElements behavior. Native Dima widgets substitute only in HTML and CSS, read JavaScript settings viaDima.fields, and receive livefieldsevents in the editor.
Limits and reliability
Section titled “Limits and reliability”| Limit | Maximum |
|---|---|
| HTML or CSS file | 512 KB each |
| JavaScript file | 1 MB |
| Fields file | 256 KB |
| Data file | 128 KB |
widget.json manifest | 16 KB |
| Whole package | 2 MB |
| Settings per widget | 500 |
| Changed settings per layer | 64 KB |
| Store value | 64 KB of JSON |
| Store keys per channel | 500 keys and 2 MB total |
| Store key name | 100 characters |
| RPC request payload | 64 KB |
| Calls from one frame | 30 RPCs per second |
| Log messages from one frame | 200 per minute |
Each widget frame emits a heartbeat every two seconds. If a frame stops responding for ten seconds, Studio reloads it up to three times within five minutes before disabling the widget with an error. RPC calls or log lines past their rate limits are dropped. Because the sandbox shares a process with the host page, a tight infinite loop can still stall rendering—keep work lightweight, avoid blocking loops, and use timers for recurring updates.
Security
Section titled “Security”Widgets run in a sandboxed iframe with scripts enabled and an opaque origin. They cannot access site storage or logins, inspect the parent page, other layers, or the private overlay URL, open popups, dialogs, downloads, or forms, or navigate the page. Only the channel owner can import or edit widget code. The widget talks to DomDimaBot through the rate-limited SDK—it can read or write its own saved values and read command counters. As a best effort, the SDK strips OBS’s window.obsstudio API before widget code runs; because inner frames or navigated pages receive a fresh copy, OBS browser source Page permissions still matter—recommend No access to OBS for sources displaying imported widgets.
By default, widget code can load files and scripts from any website, forward public channel data (chat messages, alerts, usernames) to remote servers (exposing the streaming PC’s IP address), render anything on stream, and consume CPU and memory. Remote scripts or styles run as part of the widget and can change after import. When Studio detects outside scripts or styles, the import dialog displays This widget loads code from other sites, lists the detected hosts, warns that external code can change and send received data elsewhere, and offers the owner-controlled Block outside connections for this widget checkbox (off by default). Layer settings also show Loads code from …. The owner can change Block outside connections anytime in layer settings; widget.json cannot set or override this choice.
When outside connections are blocked, the iframe enforces a Content-Security-Policy of default-src 'none' (allowing inline scripts and eval), connect-src 'none', frame-src 'none', and worker-src 'none':
- Only inline code runs—no scripts from external origins, including StreamElements. Styles may additionally load from Google Fonts.
- Images, fonts, audio, and video load only from DomDimaBot, copied assets,
cdn.streamelements.com,static.streamelements.com, Google Fonts, andstatic-cdn.jtvnw.net(Twitch emotes and badges). - Fetches, sockets, WebRTC, inner frames, and workers are blocked, DNS prefetching is disabled, and the policy is also set on the iframe’s
cspattribute—any navigation or reload attempt (even before initial load) is stopped. - The widget’s own inline code and settings keep working. Bundle libraries inline or use copied files; widgets relying on external CDNs like cdnjs or jsDelivr or external fonts may fail to load.
- Studio’s preview enforces the exact same rule, and connected OBS sources reload immediately whenever the owner toggles it.
- This blocks typical tracking, uploads, and remote code changes, but is not airtight against a determined author: the HTTP request for a blocked navigation fires before the frame is stopped, and explicit DNS hints can still resolve.
Finally, the SDK provides an in-memory shim for localStorage and sessionStorage—do not expect values stored there to persist across reloads. Widgets only receive the live categories declared in uses. Always escape viewer-supplied text before injecting it into HTML, or use textContent for plain text.