Skip to main content

JavaScript framework

We provide a JavaScript framework intended to help you in the development of adapters, overlays and docks. Below you will find all the exposed constants, functions and classes, grouped by category.

Common code

This code is exported by all the JavaScript files listed below.

Constants

nametypevalue
loadstring'load'
sessionstring'session'
alertsstring'alerts'
chatstring'chat'
otherstring'other'
facebookstring'facebook'
trovostring'trovo'
twitchstring'twitch'
youtubestring'youtube'
eventstring'event'
merchstring'merch'
tipstring'tip'
redemptionstring'redemption'
rewardstring'reward'
subscriberstring'subscriber'
cheerstring'cheer'
elixirstring'elixir'
followerstring'follower'
raidstring'raid'
sponsorstring'sponsor'
superChatstring'superchat'
fanstring'fan'
videoLikestring'videolike'
supporterstring'supporter'
sharestring'share'
starsstring'stars'
messagestring'message'
deleteMessagestring'delete-message'
deleteMessagesstring'delete-messages'
botCounterstring'bot:counter'

Events

Listener

The Listener class is used to make it easier to listen to events. Its TypeScript signature is as follows:

type Callback = (event: Event) => any;

declare class Listener {
constructor(event: string, callback: Callback, host?: EventTarget, passive?: false);
on(): void;
off(): void;
}
Parameters
namedescriptionoptional
eventName of the event to listen tono
callbackFunction called on eventno
hostObject to listen to the event onyes (window by default)
passiveDefines whether the event is passive (true) or not (false)yes (true by default)
Methods
namedescription
onStart listening for the event (called on initialization)
offStop listening to the event
Example
const listener = new Listener('click', console.log, document.body);

listener.off();
listener.on();

adapters.js file

The adapters.js file contains everything that may be useful for adapter development, in addition to the common code described above.

<script type="module">
import {} from 'https://obs.multistream.tools/v1/adapters.js';
</script>
danger

Do not add any hash or query string to the file import URL, otherwise the module would be executed several times instead of just once, which could give rise to unwanted side effects.

Constants

nametypevalue
wildCardstring'*'
onWidgetLoadstring'onWidgetLoad'
onEventReceivedstring'onEventReceived'
onSessionUpdatestring'onSessionUpdate'

Platforms

The Platform, Facebook, Trovo, Twitch and YouTube classes are described on the page dedicated to platforms.

Adapters

The classes Adapter, StreamElementsAdapter, FacebookStreamElementsAdapter, TrovoStreamElementsAdapter, TwitchStreamElementsAdapter and YouTubeStreamElementsAdapter are described on the page dedicated to adapters.

overlay.js file

The overlay.js file contains everything that can be useful for developing overlays and docks, in addition to the common code described above.

<script type="module">
import {} from 'https://obs.multistream.tools/v1/overlay.js';
</script>
danger

Do not add any hash or query string to the file import URL, otherwise the module would be executed several times instead of just once, which could give rise to unwanted side effects.

Constants

nametypevalue
mutestring'mute'
pausestring'pause'
skipstring'skip'

Shortcuts

namevalue
fromArray.from
isArrayArray.isArray
parseJSON.parse
stringifyJSON.stringify
assignObject.assign
createObject.create
entriesObject.entries
keysObject.keys
originlocation.origin
pathnamelocation.pathname
searchlocation.search
htmldocument.documentElement
headdocument.head
bodydocument.body

Utilities

isString

The isString function allows you to know whether the value passed as a parameter is a string or not. Its TypeScript signature is as follows:

declare const isString: (value: any) => boolean;
Parameters
namedescriptionoptional
valueValue to testno
Example
isString(''); // true
isString({}); // false

isNumber

The isNumber function allows you to know whether the value passed as a parameter is a number or not. Its TypeScript signature is as follows:

declare const isNumber: (value: any) => boolean;
Parameters
namedescriptionoptional
valueValue to testno
Example
isNumber(1); // true
isNumber('1'); // false

isTrue

The isTrue function allows you to know whether the value passed as a parameter is true or not. Its TypeScript signature is as follows:

declare const isTrue: (value: any) => boolean;
Parameters
namedescriptionoptional
valueValue to testno
Example
isTrue(true); // true
isTrue('true'); // false
isTrue(new Boolean(true)); // false

validate

The validate function allows you to test whether the value passed as a parameter satisfies a given predicate; if the predicate returns true, the call to the validate function returns the value passed as a parameter. Its TypeScript signature is as follows:

type Predicate = (value: any) => boolean;

declare const validate: (predicate: Predicate, value: any, fallback?: any) => any;
Parameters
namedescriptionoptional
predicateTest predicateno
valueValue to testno
fallbackDefault valueyes (undefined by default)
Example
let { exampleParam } = parameters;

exampleParam = validate(isString, exampleParam, ''); // `exampleParam` or `''`

validateString

The validateString function allows you to test whether the value passed as a parameter is a string; if so, the call to the validateString function returns the value passed as a parameter. Its TypeScript signature is as follows:

declare const validateString: (value: any, fallback?: any) => any;
Parameters
namedescriptionoptional
valueValue to testno
fallbackDefault valueyes ('' by default)
Example
let { exampleParamA, exampleParamB } = parameters;

exampleParamA = validateString(exampleParamA); // `exampleParamA` or `''`
exampleParamB = validateString(exampleParamB, 'fallback'); // `exampleParamB` or `'fallback'`
validateString('', 'fallback'); // 'fallback'

validateNumber

The validateNumber function allows you to test whether the value passed as a parameter is a number; if so, the call to the validateNumber function returns the value passed as a parameter. Its TypeScript signature is as follows:

declare const validateNumber: (value: any, fallback?: any) => any;
Parameters
namedescriptionoptional
valueValue to testno
fallbackDefault valueyes (undefined by default)
Example
let { exampleParamA, exampleParamB } = parameters;

exampleParamA = validateNumber(exampleParamA); // `exampleParamA` or `undefined`
exampleParamB = validateNumber(exampleParamB, 42); // `exampleParamB` or `42`
validateNumber(0, 9000); // 0

validateArray

The validateArray function allows you to test whether the value passed as a parameter is a string; if so, the call to the validateArray function returns an array containing the values ​​passed as parameter separated by commas. Its TypeScript signature is as follows:

type Mapper = (value: string) => any;

declare const validateArray: (value: string, fallback?: string, mapper?: Mapper) => any[];
Parameters
namedescriptionoptional
valueValue to testno
fallbackDefault valueyes
mapperA function used to modify each value of the arrayyes
Example
let { exampleParamA, exampleParamB, exampleParamC } = parameters;

exampleParamA = validateArray(exampleParamA); // instanceof Array
exampleParamB = validateArray(exampleParamB, 'valueA,valueB'); // instanceof Array
exampleParamC = validateArray(exampleParamC, undefined, value => value.toLowerCase()); // instanceof Array

validateSet

The validateSet function allows you to test whether the value passed as a parameter is a string; if so, the call to the validateSet function returns an instance of the native Set class containing the values ​​passed as parameter separated by commas. Its TypeScript signature is as follows:

type Mapper = (value: string) => any;

declare const validateSet: (value: string, fallback?: string, mapper?: Mapper) => Set<any>;
Parameters
namedescriptionoptional
valueValue to testno
fallbackDefault valueyes
mapperA function used to modify each value of the setyes
Example
let { exampleParamA, exampleParamB, exampleParamC } = parameters;

exampleParamA = validateSet(exampleParamA); // instanceof Set
exampleParamB = validateSet(exampleParamB, 'valueA,valueB'); // instanceof Set
exampleParamC = validateSet(exampleParamC, undefined, value => value.toLowerCase()); // instanceof Set

ensureArray

The ensureArray function ensures that the value passed as a parameter is a data array and performs the conversion if this is not the case; so-called falsy values ​​are filtered. Its TypeScript signature is as follows:

declare const ensureArray: (value: any | any[]) => any[];
Parameters
namedescriptionoptional
valueValue to convert to an array if necessaryno
Example
ensureArray(['']); // []
ensureArray(''); // []
ensureArray([{}]); // [{}]
ensureArray({}); // [{}]

setWithValues

The setWithValues function allows you to initialize an instance of the Set class containing the values ​​passed as parameters, one or more in the form of an array; so-called falsy values ​​are filtered. Its TypeScript signature is as follows:

declare const setWithValues: (value: any | any[]) => Set<any>;
Parameters
namedescriptionoptional
valueValue(s) contained in the created Setno
Example
setWithValues(['', {}]).size; // 1
setWithValues('').size; // 0
setWithValues({}).size; // 1

alias

The alias function allows you to lock the first parameters of a given function; if the value of the first parameter is an array, the return value will be an array of functions. Its TypeScript signature is as follows:

type Callback = (...args: any[]) => any;

declare const alias: (callback: Callback, first: any | any[], ...args: any[]) => Callback | Callback[];
Parameters
namedescriptionoptional
callbackFunction for which we want to lock the parametersno
firstFirst parameter to lock, treated differently if it is an arrayno
...argsPossible additional parametersyes
Example
const [log1, log2] = alias(console.log, [1, 2]);
log1(2); // 1 2
log2(3); // 2 3

const log3 = alias(console.log, 3, 4);
log3(5, 6); // 3 4 5 6

get

The get function allows you to retrieve or assign the value stored in a given map for a given key; if no truthy value exists, an instance of the class passed as a parameter will be created, stored and returned. Its TypeScript signature is as follows:

type Class = {
new (...args: any[]): any;
};

declare const get: (map: Map<any, any>, key: any, Class: Class) => any;
Parameters
namedescriptionoptional
mapInstance of the Map class on which to retrieve or assign the valueno
keyKey for which to retrieve or assign the value on the mapno
ClassClass instantiated and stored in the map if no truthy value exists for the given keyno
Example
const key1 = 'key1';
const map = new Map([[key1, 1]]);

get(map, key1, Set); // 1
get(map, 'key2', Set); // instanceof Set

getSafeMap

The getSafeMap function allows you to construct a safe copy for indexing of an object passed as a parameter, that is to say without a prototype chain. Its TypeScript signature is as follows:

declare const getSafeMap: (object: object) => object;
Parameters
namedescriptionoptional
objectObject of which to create a safe copy for indexingno
Example
const key = 'key';
const object = { [key]: 'value' };

object[key]; // 'value'
typeof object.hasOwnProperty; // 'function'

const safeObject = getSafeMap(object);

safeObject[key]; // 'value'
typeof safeObject.hasOwnProperty; // 'undefined'

toMilliSeconds

The toMilliSeconds function allows you to convert into milliseconds a number of seconds passed as a parameter. Its TypeScript signature is as follows:

declare const toMilliSeconds: (seconds: number) => number;
Parameters
namedescriptionoptional
secondsNumber of seconds to convert to millisecondsno
Example
toMilliSeconds(5); // 5000

Mappings

Mapping

The Mapping class is used to associate different events for different platforms, for example to group follower (Twitch) and subscriber (YouTube) events with a similar meaning; this is a subclass of the native String class. Its TypeScript signature is as follows:

type Mappings = {
[platform: string]: string;
};

type Mapped = string | Mapping;

declare class Mapping extends String {
constructor(event: string, mappings: Mappings, group?: true);
get group(): boolean;
map(platform: string): Mapped;
is(event: Mapped, platform: string): boolean;
format(): string;
}
Parameters
namedescriptionoptional
eventBasis event name, the most common oneno
mappingsObject defining variants for specific platformsno
groupIndicates whether the event can be a group (see adapters)yes
Properties
namedescription
groupIndicates whether the event can be a group
Methods
namedescription
mapReturns the variant associated with the given platform, or the mapping itself
isReturns true if the event passed as a parameter corresponds to the given platform, false otherwise
formatReturns a formatted representation of the mapping, useful in particular for possible display
Example
const cheerMapping = new Mapping(cheer, {
[trovo]: elixir,
[youtube]: superChat
});

cheerMapping.group; // false
cheerMapping.map(trovo); // elixir
cheerMapping.map(twitch); // cheerMapping
cheerMapping.map(youtube); // superChat
cheerMapping.is(follower, trovo); // false
cheerMapping.is(cheer, twitch); // true
cheerMapping.is(superChat, youtube); // true
cheerMapping.format(); // 'cheer, elixir (trovo), superchat (youtube)'

Pre-configured

We provide the following mappings, ready-to-use, to save you from having to model them yourself.

mappingevents
cheerMappingcheer, stars (Facebook), elixir (Trovo), superChat (YouTube)
followerMappingfollower, fan (Facebook), subscriber (YouTube)
merchMappingmerch
raidMappingraid
shareMappingshare
subscriberMappingsubscriber, supporter (Facebook), sponsor (YouTube)
tipMappingtip
videoLikeMappingvideoLike

URL

getOrigin

The getOrigin function allows you to extract the origin of a URL passed as a parameter. Its TypeScript signature is as follows:

declare const getOrigin: (url: string) => string;
Parameters
namedescriptionoptional
urlURL for which we want to extract the originno
Example
getOrigin('https://obs.multistream.tools/v1/overlay.js'); // 'https://obs.multistream.tools'

getParams

The getParams function allows you to construct an object from a query string passed as a parameter. Its TypeScript signature is as follows:

type Params = {
[key: string]: boolean | number | string | null | undefined;
};

declare const getParams: (queryString: string) => Params;
Parameters
namedescriptionoptional
queryStringQuery string with or without '?' at the beginningno
Example
getParams('?param1=a&param2=1&param3'); // { param1: 'a', param2: 1, param3: true }

split

The split function allows you to separate several values, delimited by commas, from a string passed as a parameter. Its TypeScript signature is as follows:

declare const split: (value: string) => string[];
Parameters
namedescriptionoptional
valuePotentially multiple values ​​separated by commasno
Example
split('value1,value2'); // ['value1', 'value2']

parameters

The parameters object contains the parameters applied to the current page through the query string, except the lang, fonts, theme and zoom parameters. This object is safe for indexing. The system parameters are described in detail on the page dedicated to overlays.

reloadPage

The reloadPage function allows you to reload the current page. Its TypeScript signature is as follows:

declare const reloadPage: () => void;

showTab

The showTab function allows displaying a given tab (see our CSS framework) from a DOM element passed as a parameter, navigation can be optional thanks to the force parameter. Its TypeScript signature is as follows:

declare const showTab: (element: HTMLElement, force?: false) => void;
Parameters
namedescriptionoptional
elementMust contain an id property whose value matches that of a tabno
forceForce (true) or not (false) navigation if another tab already is displayedyes (true by default)
Example
const tab1 = document.getElementById('tab1');
const tab2 = document.getElementById('tab2');

showTab(tab1);
showTab(tab2, false);

DOM

prepend

The prepend function allows you to insert content at the start of a given DOM element, one or more values ​​in the form of an array; so-called falsy values ​​are filtered. Its TypeScript signature is as follows:

type Content = string | HTMLElement;

declare const prepend: (content: Content | Content[], host?: HTMLElement) => HTMLElement;
Parameters
namedescriptionoptional
contentContent to insertno
hostElement to insert content intoyes (document.body by default)
Parameters
const world = document.createElement('p');
world.textContent = 'world';

prepend(['hello', world, null]); // document.body
prepend('hello world'); // document.body

append

The append function works in the same way as the prepend function except that it allows you to insert content at the end of a given DOM element.

replaceChildren

The replaceChildren function works in the same way as the prepend function with the difference that it allows you to completely replace the content of a given DOM element.

removeChildren

The removeChildren function allows you to remove the content of a given DOM element. Its TypeScript signature is as follows:

declare const removeChildren: (host?: HTMLElement) => HTMLElement;
Parameters
namedescriptionoptional
hostElement to remove content foryes (document.body by default)
Example
const hello = document.createElement('p');
hello.textContent = 'hello';

removeChildren(); // document.body
removeChildren(hello); // hello

setClasses

The setClasses function allows you to add/remove CSS classes to a DOM element, one or more values ​​in the form of an array; so-called falsy values ​​are filtered. Its TypeScript signature is as follows:

declare const setClasses: (classes: string | string[], host?: HTMLElement, add?: false) => HTMLElement;
Parameters
namedescriptionoptional
classesCSS classes to add or removeno
hostElement to add/remove classes toyes (document.body by default)
addAdd (true) or remove (false) classesyes (true by default)
Example
setClasses(['classA', 'classB']); // document.body
setClasses('classB', undefined, false); // document.body

setData

The setData function allows you to add and reset data to a given DOM element. Its TypeScript signature is as follows:

declare const setData: (data: object, host?: HTMLElement, reset?: true) => HTMLElement;
Parameters
namedescriptionoptional
dataData to add to the elementno
hostElement to add/reset data toyes (document.body by default)
resetReset (true) or not (false) datayes (false by default)
Example
setData({ data1: 1 }); // document.body
setData({ data2: 2 }, undefined, true); // document.body
setData(null, undefined, true); // document.body

element

The element function allows you to create a DOM element, optionally adding CSS classes, content, data and properties to it; so-called falsy values ​​are filtered for CSS classes and content. Its TypeScript signature is as follows:

type Content = string | HTMLElement;

type Properties = {
classes?: string | string[];
content: Content | Content[];
data?: object;
[key: string]: any;
};

declare const element: (tag: string, properties?: Properties) => HTMLElement;
Parameters
namedescriptionoptional
tagTag of the element to createno
propertiesProperties to initialize on the created elementyes
Example
element('div'); // instanceof HTMLDivElement

element('p', {
classes: 'classA',
content: 'hello world',
data: { data1: 1 },
id: 'elementId'
}); // instanceof HTMLParagraphElement

button

The button function is a shortcut to the element function allowing you to create elements of type button; the properties parameter remains unchanged.

input

The input function is a shortcut to the element function allowing you to create elements of type input; the properties parameter remains unchanged.

label

The label function is a shortcut to the element function allowing you to create elements of type label; the properties parameter remains unchanged.

li

The li function is a shortcut to the element function allowing you to create elements of type li; the properties parameter remains unchanged.

The link function is a shortcut to the element function allowing you to create elements of type link; the properties parameter remains unchanged.

span

The span function is a shortcut to the element function allowing you to create elements of type span; the properties parameter remains unchanged.

enable

The enable function allows you to enable or disable a DOM element (interactive one). Its TypeScript signature is as follows:

type Host = HTMLButtonElement | HTMLFieldSetElement | HTMLOptGroupElement | HTMLOptionElement | HTMLSelectElement | HTMLTextAreaElement | HTMLInputElement;

declare const enable: (host: Host, enabled?: false) => Host;
Parameters
namedescriptionoptional
hostElement to enable/disableno
enabledEnable (true) or disable (false) the elementyes (true by default)
Example
const button = element('button');

enable(button); // button
enable(button, false); // button

getValue

The getValue function allows you to retrieve the value of the value property of a DOM element; depending on the parameters passed as input, this value can be a list. Its TypeScript signature is as follows:

type ValueNode = Node & {
value: string;
};

type Host = ValueNode | RadioNodeList | undefined | null;

declare const getValue: (host: Host, multiple?: true) => any | any[];
Parameters
namedescriptionoptional
hostElement for which to retrieve the value of the value propertyno
multipleIndicates whether the element should be treated as a list (true) or not (false)yes (false by default)
Example
const input = element('input', { value: 'hello world' });

getValue(input); // 'hello world'
getValue(input, true); // ['hello world']
getValue(undefined); // undefined
getValue(undefined, true); // []

crossOrigin

The crossOrigin function allows you to configure the value of the crossOrigin property of a DOM element. Its TypeScript signature is as follows:

type Host = HTMLAudioElement | HTMLImageElement | HTMLLinkElement | HTMLScriptElement | HTMLVideoElement;

type Value = 'anonymous' | 'use-credentials' | '';

declare const crossOrigin: (host: Host, value?: Value) => Host;
Parameters
namedescriptionoptional
hostElement for which to configure the crossOrigin property valueno
valueValue to configure for the crossOrigin propertyyes ('anonymous' by default)
Example
const image = element('img');

crossOrigin(image); // image
crossOrigin(image, 'use-credentials'); // image

hide

The hide function allows you to hide or show a given DOM element by adding or removing the hidden class, exposed by our CSS framework. Its TypeScript signature is as follows:

declare const hide: (hidden?: false, host?: HTMLElement) => HTMLElement;
Parameters
namedescriptionoptional
hiddenHide (true) or show (false) the given elementyes (true by default)
hostElement to hide or showyes (document.body by default)
Example
hide(); // document.body
hide(false); // document.body

setText

The setText function allows you to modify the textual content of a given DOM element. Its TypeScript signature is as follows:

declare const setText: (text: string, host?: HTMLElement) => HTMLElement;
Parameters
namedescriptionoptional
textNew text content for the given elementno
hostElement for which to modify the textual contentyes (document.body by default)
Example
setText('hello world'); // document.body

setVariable

The setVariable function allows you to configure/delete the value of a CSS variable on a given DOM element. Its TypeScript signature is as follows:

type Value = string | number | undefined | null;

declare const setVariable: (name: string, value: Value, host?: HTMLElement) => HTMLElement;
Parameters
namedescriptionoptional
nameName of the CSS variable to configureno
valueValue of the CSS variable to configure, undefined or null to deleteno
hostElement on which to modify the CSS variableyes (document.documentElement by default)
Example
setVariable('hello world'); // document.body

select

The select function allows you to retrieve an array of DOM elements by CSS selector. Its TypeScript signature is as follows:

declare const select: (selector: string, host?: HTMLElement) => HTMLElement[];
Parameters
namedescriptionoptional
selectorCSS selector to locate elementsno
hostElement to select elements fromyes (document.documentElement by default)
Example
select('meta'); // HTMLMetaElement[]
select('div', body); // HTMLDivElement[]

Events

ClickListener

The ClickListener class is a subclass of the Listener class described previously; this is used to facilitate listening to events of type click. Its TypeScript signature is as follows:

declare class ClickListener extends Listener {
constructor(callback: Callback, host?: EventTarget, passive?: false);
}

Namespace

Namespace

The Namespace class is used to create a namespace in order to avoid possible collisions. The generated keys are automatically prefixed by the origin of the current page; a custom suffix can be added if needed. Its TypeScript signature is as follows:

declare class Namespace {
constructor(suffix?: string, prefix?: string);
key(name: string): string;
}
Parameters
namedescriptionoptional
suffixCustom suffix for all generated keysyes
prefixCustom prefix for all generated keysyes (origin by default)
Methods
namedescription
keyGenerate a prefixed key to avoid naming conflicts
Example
const namespaceA = new Namespace();
namespaceA.key('keyName'); // '<currentPageOrigin>.keyName'

const namespaceB = new Namespace('suffixName');
namespaceB.key('otherName'); // '<currentPageOrigin>suffixName.otherName'

Persistence

Store

The Store class is used to save data to the local storage of the browser; this is a subclass of the Namespace class described previously. The storage keys are automatically prefixed by the address (origin + pathname) of the current page to avoid any possible conflict. Its TypeScript signature is as follows:

declare class Store extends Namespace {
constructor(suffix?: false | null | string);
set(key: string, value: any): void;
get(key: string): any | null;
remove(key: string): void;
}
Parameters
namedescriptionoptional
suffixCustom suffix for all generated keys, makes sharing storage easieryes (pathname by default)
Methods
namedescription
getRetrieve a previously stored value for a given key
setStore/overwrite a value for a given key
removeDelete a previously stored value for a given key
Example
const store = new Store();
const key = 'counter';

store.get(key); // null
store.set(key, 1);
store.set(key, 2);
store.get(key); // 2
store.remove(key);

Forms

Form

The Form class is used to add behavior to a form such as persisting the values ​​of certain fields; this is a subclass of the Store class described previously. Its TypeScript signature is as follows:

type ResetCallback = () => any;

type ChangeCallback = (name: string, element: HTMLElement) => any;

type SubmitCallback = (event: SubmitEvent) => any;

type Options = {
persisted?: string[] | true;
reset?: ResetCallback | false;
change?: ChangeCallback;
submit: SubmitCallback;
};

type FieldBuilder = (removeButton: HTMLButtonElement) => HTMLElement;

declare class Form extends Store {
constructor(host: HTMLFormElement, options: Options, suffix?: false | null | string);
buildRemovableField(fieldBuilder: FieldBuilder, buttonText?: string): HTMLElement;
addRemovableFieldOnClick(clickHost: HTMLElement, addHost: HTMLElement, fieldBuilder: FieldBuilder, buttonText?: string): ClickListener;
}
Parameters
namedescriptionoptional
hostForm element to add behavior tono
optionsObject describing the behavior to add to the formno
options.persistedList of field names (name attribute) whose (valid) value must be persisted, or true for allyes
options.resetFunction to call after resetting the form, pass false if it does not have a reset buttonyes
options.changeFunction to call when the values of the persisted fields change, if validyes
options.submitFunction to call on form submission (the event.preventDefault method is called internally)no
suffixCustom suffix for all generated keys, makes sharing storage easieryes (pathname by default)
Methods
namedescription
buildRemovableFieldCreate a field that can be deleted by clicking a button
addRemovableFieldOnClickAdd fields, which can be deleted, to a list by clicking on a given element
info

The addRemovableFieldOnClick method calls buildRemovableField internally, our dock relies on it for example in its Settings tab.

The default delete button text is 'Remove' and the danger CSS class automatically is added to it.

Example
const formElement = document.getElementById('form');

const form = new Form(formElement, {
persisted: ['fieldA', 'fieldB'], // Pass `true` to persist all fields.
reset: false,
change(fieldName, field) {
console.log('change', fieldName, field);
},
submit(event) {
console.log('submit', event);
}
});

const itemBuilder = removeButton => li({
content: [element('input'), removeButton]
});

form.buildRemovableField(itemBuilder); // instanceof HTMLLIElement

const addButton = document.getElementById('add');
const fieldsList = document.getElementById('list');

form.addRemovableFieldOnClick(addButton, fieldsList, itemBuilder, 'Delete'); // instanceof ClickListener

Waiting queue

Queue

The Queue class is used to create and manage FIFO (First In First Out) queues. Its TypeScript signature is as follows:

type Callback = () => void;

declare class Queue {
constructor(duration?: number, manual?: true);
add(onStart: Callback, onEnd: Callback): void;
pause(paused?: false): void;
skip(): void;
clear(): void;
dispose(): void;
}
Parameters
namedescriptionoptional
durationHold duration, expressed in secondsyes (parameters.queueDuration by default)
manualAutomatically react (false) or not (true) to pause and skip system eventsyes (false by default)
Methods
namedescription
addAdd a new item to the queue
pausePause or resume the execution of the queue
skipDirectly go to the next item in the queue, has no effect when the queue is paused
clearAllows you to completely empty the queue
disposeCleanup method to call, when the manual parameter is false, if the instance is no longer used or you want to disconnect it from system events
info

The onStart and onEnd functions are respectively called when an element starts to exit the queue and after it has completely exited.

Example
const queue = new Queue(25);

[1, 2, 3].forEach(number => queue.add(
() => console.log('onStart', number),
() => console.log('onEnd', number)
));

queue.pause();
queue.pause(false);
queue.skip();
queue.clear();
queue.dispose();

Spam

AntiSpam

The AntiSpam class is used to check that a given action is not considered spam. Its TypeScript signature is as follows:

declare class AntiSpam {
constructor(threshold?: number, delta?: number);
check(action: any): boolean;
}
Parameters
namedescriptionoptional
thresholdMaximum number of accepted repetitions for the same actionyes (parameters.antiSpamThreshold by default)
deltaDuration after which the same action will no longer be considered spam, expressed in secondsyes (parameters.antiSpamDelta by default)
Methods
namedescription
checkReturns true if the given action is not considered spam, false otherwise
Example
const antiSpam = new AntiSpam(2, 0.5);
const action = 'action';

antiSpam.check(action); // true
antiSpam.check(action); // true
antiSpam.check(action); // false

Audio

Sound

The Sound class is used to play audio files; this is a subclass of the native Audio class, simply adding missing amenities. Its TypeScript signature is as follows:

type CrossOrigin = 'anonymous' | 'use-credentials' | '';

declare class Sound extends Audio {
constructor(url: string, volume?: number, crossOrigin?: CrossOrigin, manual?: true);
stop(): void;
mute(muted?: false): void;
dispose(): void;
}
Parameters
namedescriptionoptional
urlAddress of the audio file to loadno
volumeAudio file playback volume, between 0 and 1yes (parameters.volume by default)
crossOriginValue to configure for the crossOrigin propertyyes ('anonymous' by default)
manualAutomatically react (false) or not (true) to mute system eventsyes (false by default)
Methods
namedescription
stopCompletely stop playing the audio file
muteMute (true) or unmute (false) the sound without stopping the playback of the audio file
disposeCleanup method to call, when the manual parameter is false, if the instance is no longer used or you want to disconnect it from system events
Example
const sound = new Sound('<fileURL>', 0.5);

sound.play();
sound.mute();
sound.mute(false);
sound.stop();
sound.dispose();

Communication

Emitter

The Emitter class is used to emit custom events in our system; this is a subclass of the Namespace class described previously. Its TypeScript signature is as follows:

declare class Emitter extends Namespace {
constructor(crossOrigin?: boolean, namespace?: string);
emit(category: string, data?: any, otherProperties?: object): void;
}
Parameters
namedescriptionoptional
crossOriginIndicates whether emitted events can be received by overlays of different origins (true)yes (false by default)
namespaceAdds a namespace to emitted events, recommended when crossOrigin is trueyes
Methods
namedescription
emitEmit custom events
Example
const emitter = new Emitter();
const category = 'customEvent';
const props = { key: 'value' };
const data = { props };

emitter.emit(category); // Emitted event: { category }
emitter.emit(category, data); // Emitted event: { category, data }
emitter.emit(category, data, props); // Emitted event: { category, data, ...props }
emitter.emit(category, undefined, props); // Emitted event: { category, ...props }

Observer

The Observer class is used to listen to events emitted in our system, native or custom ones; this is a subclass of the Listener class described previously. Its TypeScript signature is as follows:

type Id = string;

type AlertData = {
name: string;
sender?: string;
message?: string;
tier?: string;
amount?: number;
};

type SessionData = {
[key: string]: object | object[];
};

type LoadData = {
session: SessionData;
};

type ChatData = object;

type MessageData = {
renderedText: string;
data: {
userId: Id;
msgId: Id;
nick: string;
displayName: string;
};
};

type DeleteMessageData = {
msgId: Id;
};

type DeleteMessagesData = {
userId: Id;
};

type OtherData = object;

type Event<T = undefined, U = undefined> = {
data: T;
event: U;
[key: string]: any;
};

type PlatformEvent<T, U = undefined> = Event<T, U> & {
platform: string;
group?: Id;
root?: true;
};

type Callback<T> = (event: T) => any;

type SystemEvents = {
load?: Callback<PlatformEvent<LoadData>>;
session?: Callback<PlatformEvent<SessionData>>;
alerts?: Callback<PlatformEvent<AlertData, string>>;
chat?: Callback<
PlatformEvent<MessageData, 'message'> |
PlatformEvent<DeleteMessageData, 'delete-message'> |
PlatformEvent<DeleteMessagesData, 'delete-messages'> |
PlatformEvent<ChatData, string>
>;
other?: Callback<PlatformEvent<OtherData, string>>;
mute?: Callback<Event<boolean>>;
pause?: Callback<Event<boolean>>;
skip?: Callback<Event>;
};

type CustomEvents = {
[key: string]: Callback<Event<any, any>>;
};

type Events = SystemEvents | CustomEvents;

declare class Observer extends Listener {
constructor(events: Events);
}
Parameters
namedescriptionoptional
eventsObject listing the functions to call upon receipt of given eventsno
Example
const logger = type => data => console.log(type, data);

const emitter = new Emitter();
const customEvent = 'customEvent';

const observer = new Observer({
// System events.
load: logger('load'),
session: logger('session'),
alerts: logger('alerts'),
chat: logger('chat'),
other: logger('other'),
mute: logger('mute'),
pause: logger('pause'),
skip: logger('skip'),
// OBS related system events.
getCurrentScene: logger('getCurrentScene'),
obsSceneChanged: logger('obsSceneChanged'),
// Custom event.
[emitter.key(customEvent)]: logger(customEvent)
});

observer.off();
observer.on();

OBS

obsAPI

The obsAPI function allows you to use the OBS JavaScript API, the complete list of possibilities is available on this page. Its TypeScript signature is as follows:

declare const obsAPI: (method: string, ...args: any[]) => void;
Parameters
namedescriptionoptional
methodName of the method to call (getter or setter)no
...argsParameters to pass when calling the methodyes
Example
const pluginVersion = 'pluginVersion';
const getCurrentScene = 'getCurrentScene';

new Observer({
[pluginVersion]({ data }) {
// Do whatever you want with the value here.
}
[getCurrentScene]({ data }) {
// Do whatever you want with the value here.
}
});

// Getters.
obsAPI(pluginVersion);
obsAPI(getCurrentScene);

// Setters.
obsAPI('stopStreaming');
obsAPI('setCurrentScene', 'new scene name');

Theming

loadStyles

The loadStyles function allows you to load a given stylesheet. Its TypeScript signature is as follows:

type CrossOrigin = 'anonymous' | 'use-credentials' | '';

declare const loadStyles: (url: string, crossOrigin: CrossOrigin) => HTMLLinkElement;
Parameters
namedescriptionoptional
urlAddress of the stylesheet to load (local, remote, or data URL)no
crossOriginValue to configure for the crossOrigin propertyyes ('anonymous' by default)
Example
loadStyles('<stylesheetURL>'); // instanceof HTMLLinkElement
loadStyles('<stylesheetDataURL>', 'use-credentials'); // instanceof HTMLLinkElement

loadFonts

The loadFonts function allows you to load fonts via the Google Fonts API and apply them as the --fontFamily1 to --fontFamilyN CSS variables. Its TypeScript signature is as follows:

declare const loadFonts: (query: string) => HTMLLinkElement | false;
warning

If the global fonts parameter is used either to change fonts or disable them, calling the loadFonts function will have no effect and the return value will be false.

You should call this function only once to load every font you would need and rely on CSS variables to dynamically switch them later if you want to.

The value of the Google Fonts API family parameter must always come first and the value of the display parameter is block by default.

Parameters
namedescriptionoptional
queryGoogle Fonts query, without ?family=no
Example
loadFonts('Droid+Sans|Tangerine:bold&display=auto'); // instanceof HTMLLinkElement or false

Internationalization

defaultLang

The constant named defaultLang corresponds to the default value of the lang attribute set on the html tag of the Web page associated with your overlay/dock.

warning

It is important to always set a default value to this attribute for accessibility reasons and so that our internationalization system can work correctly. For example:

<html lang="en"></html>

lang

The constant named lang corresponds to the value passed as the system parameter of the same name; or to that of the navigator.language property by default, i.e. the language of the browser displaying the Web page of your overlay/dock (in this case that of the OBS user interface).

i18n

The i18n function helps with messages translation. You should only call it once and only if your overlay/dock needs to be translated into multiple languages. Its TypeScript signature is as follows:

type Translations = {
[lang: string]: object;
};

declare const i18n: (translations?: Translations) => object;
Parameters
namedescriptionoptional
translationsObjects containing translation data, indexed by languageyes
Example
// Given `lang="en"` on `html` tag, `'fr'` as `lang` system parameter value
// and `<div data-i18n="hello">Hello</div>` in `body` element.

i18n().hello; // 'Hello' (default value)

// 'Bonjour'
const { hello } = i18n({
fr: { hello: 'Bonjour' },
es: { hello: 'Holà' }
});

document.documentElement.lang; // 'fr'
info

When no translation data is passed as a parameter, the i18n function simply synchronizes the value of the lang attribute, on the html tag of the page, with the one of the constant named lang described above; this can be useful when you want to manage translations in another way.

When translation data is passed as a parameter, the i18n function seeks to determine the closest match between the defined languages and the value of the constant named lang; this match, if found, is then applied as the value of the lang attribute on the html tag of the page. For example:

// Given `lang="fr"` on `html` tag and `'en-US'` as `lang` system parameter value.

// 'Color'
const { color } = i18n({
'en-GB': { color: 'Colour' },
en: { color: 'Color' }
});

document.documentElement.lang; // 'en'

In both cases, the i18n function iterates through each DOM element on the page with a data-i18n attribute and:

  • replaces its textual content automatically with any defined translation data, of type string, whose key corresponds to the value of the data-i18n attribute in question
  • gets/returns its textual content when no translation data is defined for the key in question

The return value of the i18n function is therefore an object containing the fusion of the translation data for the desired language (if defined) and that of the default language. This object is safe for indexing.

tip

It is also possible to define translation data of types other than string, they will simply not be applied automatically but manually, as you wish. For example:

const helloEN = user => `Hello ${user}!`;

const helloFR = user => `Bonjour ${user} !`;

const { hello = helloEN } = i18n({ fr: { hello: helloFR } });

setText(hello('TheFrenchBiff'));

You can also pass translation data for the default language, which can be particularly useful in the case of dynamic messages that are not part of the initial content of the page (content for which we would prefer the use of the previously mentioned data-i18n attributes).

// Given `lang="en"` on `html` tag, `'fr'` as `lang` system parameter value
// and `<div data-i18n="hello">Hello</div>` in `body` element.

const {
hello, // 'Bonjour'
you, // 'toi'
message // 'message'
} = i18n({
[defaultLang]: { you: 'you', message: 'message' },
fr: { hello: 'Bonjour', you, 'toi' }
});

Note that it is entirely possible to omit any translation data for which the value is not different than the default one.

For a practical example, go to our page dedicated to overlay development.