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
| name | type | value |
|---|---|---|
load | string | 'load' |
session | string | 'session' |
alerts | string | 'alerts' |
chat | string | 'chat' |
other | string | 'other' |
facebook | string | 'facebook' |
kick | string | 'kick' |
tiktok | string | 'tiktok' |
trovo | string | 'trovo' |
twitch | string | 'twitch' |
youtube | string | 'youtube' |
event | string | 'event' |
merch | string | 'merch' |
tip | string | 'tip' |
redemption | string | 'redemption' |
reward | string | 'reward' |
subscriber | string | 'subscriber' |
cheer | string | 'cheer' |
elixir | string | 'elixir' |
follower | string | 'follower' |
raid | string | 'raid' |
sponsor | string | 'sponsor' |
superChat | string | 'superchat' |
fan | string | 'fan' |
like | string | 'like' |
videoLike | string | 'videolike' |
supporter | string | 'supporter' |
share | string | 'share' |
stars | string | 'stars' |
gift | string | 'gift' |
message | string | 'message' |
deleteMessage | string | 'delete-message' |
deleteMessages | string | 'delete-messages' |
botCounter | string | 'bot:counter' |
URL
parameters
The parameters object contains the parameters applied to the current page through the query string, except the lang, fonts, theme and zoom parameters (in the case of the adapters.js file) then queueDuration, antiSpamDelta, antiSpamThreshold and volume (in the case of the overlay.js file). This object is safe for indexing. The system parameters are described in detail on the page dedicated to overlays.
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;
type Options = {
delegate?: string;
passive?: false;
};
declare class Listener {
constructor(event: string, callback: Callback, host?: EventTarget, options?: Options);
on(): void;
off(): void;
}
Parameters
| name | description | optional |
|---|---|---|
event | Name of the event to listen to | no |
callback | Function called on event | no |
host | Object to listen to the event on | yes (window by default) |
options | Object describing the behavior to add to the listener | yes |
options.delegate | CSS selector to use event delegation | yes |
options.passive | Defines whether the event is passive (true) or not (false) | yes (true by default) |
Methods
| name | description |
|---|---|
on | Start listening for the event (called on initialization) |
off | Stop listening to the event |
Example
const listener = new Listener('click', e => console.log(e), document.body);
listener.off();
listener.on();
new Listener(
'click',
(target, e) => console.log(target, e),
document.body,
{ delegate: 'button.danger' }
);
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>
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
| name | type | value |
|---|---|---|
wildCard | string | '*' |
onWidgetLoad | string | 'onWidgetLoad' |
onEventReceived | string | 'onEventReceived' |
onSessionUpdate | string | 'onSessionUpdate' |
Platforms
The Platform, Facebook, Kick, TikTok, Trovo, Twitch and YouTube classes are described on the page dedicated to platforms.
Adapters
The Adapter, StreamElementsAdapter, FacebookStreamElementsAdapter, KickStreamElementsAdapter, TrovoStreamElementsAdapter, TwitchStreamElementsAdapter, YouTubeStreamElementsAdapter and TikFinityAdapter classes 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>
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
| name | type | value |
|---|---|---|
mute | string | 'mute' |
pause | string | 'pause' |
skip | string | 'skip' |
Shortcuts
| name | value |
|---|---|
arrayFrom | Array.from |
isArray | Array.isArray |
jsonParse | JSON.parse |
jsonStringify | JSON.stringify |
objectAssign | Object.assign |
objectCreate | Object.create |
objectEntries | Object.entries |
objectKeys | Object.keys |
origin | location.origin |
pathName | location.pathname |
queryString | location.search |
html | document.documentElement |
head | document.head |
body | document.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
| name | description | optional |
|---|---|---|
value | Value to test | no |
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
| name | description | optional |
|---|---|---|
value | Value to test | no |
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
| name | description | optional |
|---|---|---|
value | Value to test | no |
Example
isTrue(true); // true
isTrue('true'); // false
isTrue(new Boolean(true)); // false
isFalse
The isFalse function allows you to know whether the value passed as a parameter is false or not. Its TypeScript signature is as follows:
declare const isFalse: (value: any) => boolean;
Parameters
| name | description | optional |
|---|---|---|
value | Value to test | no |
Example
isFalse(false); // true
isFalse('false'); // false
isFalse(new Boolean(false)); // false
notTrue
The notTrue function allows you to know whether the value passed as a parameter is not true. Its TypeScript signature is as follows:
declare const notTrue: (value: any) => boolean;
Parameters
| name | description | optional |
|---|---|---|
value | Value to test | no |
Example
notTrue(false); // true
notTrue(true); // false
notFalse
The notFalse function allows you to know whether the value passed as a parameter is not false. Its TypeScript signature is as follows:
declare const notFalse: (value: any) => boolean;
Parameters
| name | description | optional |
|---|---|---|
value | Value to test | no |
Example
notFalse(true); // true
notFalse(false); // 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
| name | description | optional |
|---|---|---|
predicate | Test predicate | no |
value | Value to test | no |
fallback | Default value | yes (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
| name | description | optional |
|---|---|---|
value | Value to test | no |
fallback | Default value | yes ('' 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
| name | description | optional |
|---|---|---|
value | Value to test | no |
fallback | Default value | yes (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
| name | description | optional |
|---|---|---|
value | Value to test | no |
fallback | Default value | yes |
mapper | A function used to modify each value of the array | yes |
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
| name | description | optional |
|---|---|---|
value | Value to test | no |
fallback | Default value | yes |
mapper | A function used to modify each value of the set | yes |
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
getTruthyArray
The getTruthyArray 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 getTruthyArray: (value: any | any[]) => any[];
Parameters
| name | description | optional |
|---|---|---|
value | Value to convert to an array if necessary | no |
Example
getTruthyArray(['']); // []
getTruthyArray(''); // []
getTruthyArray([{}]); // [{}]
getTruthyArray({}); // [{}]
getTruthySet
The getTruthySet 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 getTruthySet: (value: any | any[]) => Set<any>;
Parameters
| name | description | optional |
|---|---|---|
value | Value(s) contained in the created Set | no |
Example
getTruthySet(['', {}]).size; // 1
getTruthySet('').size; // 0
getTruthySet({}).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
| name | description | optional |
|---|---|---|
callback | Function for which we want to lock the parameters | no |
first | First parameter to lock, treated differently if it is an array | no |
...args | Possible additional parameters | yes |
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
| name | description | optional |
|---|---|---|
map | Instance of the Map class on which to retrieve or assign the value | no |
key | Key for which to retrieve or assign the value on the map | no |
Class | Class instantiated and stored in the map if no truthy value exists for the given key | yes (Map by default) |
Example
const key1 = 'key1';
const map = new Map([[key1, 1]]);
get(map, key1); // 1
get(map, key1, Set); // 1
get(map, 'key2'); // instanceof Map
get(map, 'key3', Set); // instanceof Set
getSafeObject
The getSafeObject function allows you to construct a safe for indexing copy of merged objects passed as parameters, that is to say without a prototype chain. Its TypeScript signature is as follows:
declare const getSafeObject: (...objects: object[]) => object;
Parameters
| name | description | optional |
|---|---|---|
objects | Objects of which to create a safe for indexing copy | no |
Example
const key = 'key';
const object = { [key]: 'value' };
object[key]; // 'value'
typeof object.hasOwnProperty; // 'function'
const safeObject = getSafeObject(object);
safeObject[key]; // 'value'
typeof safeObject.hasOwnProperty; // 'undefined'
getSafeObject({ a: 1 }, { a: 2, b: 1 }); // { a: 2, b: 1 }
removeProperties
The removeProperties function allows you to delete properties on an object passed as parameter, by mutating it. Its TypeScript signature is as follows:
declare const removeProperties: (object: object, ...keys: string[]) => object;
Paramètres
| name | description | optional |
|---|---|---|
object | Object on which to delete properties | no |
keys | Names of the different properties to delete | yes |
Exemple
const objectA = { a: 1, b: 2, c: 3 };
removeProperties(objectA, 'a'); // objectA is now { b: 2, c: 3 }
removeProperties(objectA, 'b', 'c'); // objectA is now {}
const objectB = { a: 1, b: 2, c: 3 };
removeProperties(objectB); // objectB is now {}
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
| name | description | optional |
|---|---|---|
seconds | Number of seconds to convert to milliseconds | no |
Example
toMilliSeconds(5); // 5000
split
The split function allows you to separate several values, delimited by a given separator, from a string passed as a parameter. Its TypeScript signature is as follows:
declare const split: (value: string, separator?: string) => string[];
Parameters
| name | description | optional |
|---|---|---|
value | Potentially multiple values | no |
separator | Separator delimiting the different values | yes (',' by default) |
Example
split('value1,value2'); // ['value1', 'value2']
split('value3|value4', '|'); // ['value3', 'value4']
template
The template function allows you to replace multiple values, in a string passed as a parameter, with data also provided. Its TypeScript signature is as follows:
declare const template: (value: string, data: object) => string;
Paramètres
| name | description | optional |
|---|---|---|
value | String containing values to be replaced | no |
data | Data with which to replace these values | no |
Exemple
template('Hello {who}! {notFound}', { who: 'world' }); // 'Hello world! {notFound}'
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
| name | description | optional |
|---|---|---|
event | Basis event name, the most common one | no |
mappings | Object defining variants for specific platforms | no |
group | Indicates whether the event can be a group (see adapters) | yes |
Properties
| name | description |
|---|---|
group | Indicates whether the event can be a group |
Methods
| name | description |
|---|---|
map | Returns the variant associated with the given platform, or the mapping itself |
is | Returns true if the event passed as a parameter corresponds to the given platform, false otherwise |
format | Returns 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.
| mapping | events |
|---|---|
cheerMapping | cheer, stars (Facebook), gift (TikTok), elixir (Trovo), superChat (YouTube) |
followerMapping | follower, fan (Facebook), subscriber (YouTube) |
merchMapping | merch |
raidMapping | raid |
shareMapping | share |
subscriberMapping | subscriber, supporter (Facebook), sponsor (YouTube) |
tipMapping | tip |
likeMapping | like, videoLike (Facebook) |
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
| name | description | optional |
|---|---|---|
url | URL for which we want to extract the origin | no |
Example
getOrigin('https://obs.multistream.tools/v1/overlay.js'); // 'https://obs.multistream.tools'
getParams
The getParams function allows you to construct an object, which is safe for indexing, 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
| name | description | optional |
|---|---|---|
queryString | Query string with or without '?' at the beginning | no |
You can directly use paramName and !paramName as shortcuts for paramName=true and paramName=false respectively.
Example
getParams('?param1=a¶m2=1¶m3=-10.5¶m4&!param5'); // { param1: 'a', param2: 1, param3: -10.5, param4: true, param5: false }
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
| name | description | optional |
|---|---|---|
element | Must contain an id property whose value matches that of a tab | no |
force | Force (true) or not (false) navigation if another tab already is displayed | yes (true by default) |
Example
const tab1 = document.getElementById('tab1');
const tab2 = document.getElementById('tab2');
showTab(tab1);
showTab(tab2, false);
zoom
The constant named zoom corresponds to the value passed as the system parameter of the same name; or 1 by default.
queueDuration
The constant named queueDuration corresponds to the value passed as the system parameter of the same name; or 10 by default.
antiSpamDelta
The constant named antiSpamDelta corresponds to the value passed as the system parameter of the same name; or 1 by default.
antiSpamThreshold
The constant named antiSpamThreshold corresponds to the value passed as the system parameter of the same name; or 3 by default.
volume
The constant named volume corresponds to the value passed as the system parameter of the same name; or 1 by default.
HTTP
request
The request function allows you to initiate HTTP requests. It's a simple wrapper around the window.fetch method, working exactly the same way, the only difference being that an error is actually returned if the response is an error.
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
| name | description | optional |
|---|---|---|
content | Content to insert | no |
host | Element to insert content into | yes (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
| name | description | optional |
|---|---|---|
host | Element to remove content for | yes (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
| name | description | optional |
|---|---|---|
classes | CSS classes to add or remove | no |
host | Element to add/remove classes to | yes (document.body by default) |
add | Add (true) or remove (false) classes | yes (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
| name | description | optional |
|---|---|---|
data | Data to add to the element | no |
host | Element to add/reset data to | yes (document.body by default) |
reset | Reset (true) or not (false) data | yes (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
| name | description | optional |
|---|---|---|
tag | Tag of the element to create | no |
properties | Properties to initialize on the created element | yes |
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. Its TypeScript signature is as follows:
type Type = 'button' | 'reset' | 'submit';
declare const button: (properties?: Properties, type?: Type) => HTMLButtonElement;
Parameters
| name | description | optional |
|---|---|---|
properties | Properties to initialize on the created button | yes |
type | Value to configure for the type property | yes ('button' by default) |
Example
button(); // instanceof HTMLButtonElement
button({ content: 'Click me!' }, 'submit'); // instanceof HTMLButtonElement
img
The img function is a shortcut to the element function allowing you to create elements of type img; the properties parameter remains unchanged. Its TypeScript signature is as follows:
type CrossOrigin = 'anonymous' | 'use-credentials' | '';
declare const img: (src: string, properties?: Properties, crossOrigin?: CrossOrigin) => HTMLImageElement;
Parameters
| name | description | optional |
|---|---|---|
src | Source of the image to create | no |
properties | Properties to initialize on the created image | yes |
crossOrigin | Value to configure for the crossOrigin property | yes ('anonymous' by default) |
Example
const src = 'https://example.com/image.jpg';
img(src); // instanceof HTMLImageElement
img(src, { classes: 'classA' }, 'use-credentials'); // instanceof HTMLImageElement
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.
fieldset
The fieldset function is a shortcut to the element function allowing you to create elements of type fieldset; the properties parameter remains unchanged.
div
The div function is a shortcut to the element function allowing you to create elements of type div; 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
| name | description | optional |
|---|---|---|
host | Element to enable/disable | no |
enabled | Enable (true) or disable (false) the element | yes (true by default) |
Example
const button = element('button');
enable(button); // button
enable(button, false); // button
getInputValue
The getInputValue function allows you to retrieve the value of the value property of a DOM element; depending on the parameters, 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 getInputValue: (host: Host, multiple?: true) => any | any[];
Parameters
| name | description | optional |
|---|---|---|
host | Element for which to retrieve the value of the value property | no |
multiple | Indicates 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' });
getInputValue(input); // 'hello world'
getInputValue(input, true); // ['hello world']
getInputValue(undefined); // undefined
getInputValue(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
| name | description | optional |
|---|---|---|
host | Element for which to configure the crossOrigin property value | no |
value | Value to configure for the crossOrigin property | yes ('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
| name | description | optional |
|---|---|---|
hidden | Hide (true) or show (false) the given element | yes (true by default) |
host | Element to hide or show | yes (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
| name | description | optional |
|---|---|---|
text | New text content for the given element | no |
host | Element for which to modify the textual content | yes (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
| name | description | optional |
|---|---|---|
name | Name of the CSS variable to configure | no |
value | Value of the CSS variable to configure, undefined or null to delete | no |
host | Element on which to modify the CSS variable | yes (document.documentElement by default) |
Example
setVariable('hello world'); // document.body
selectAll
The selectAll function allows you to retrieve an array of DOM elements by CSS selector. Its TypeScript signature is as follows:
declare const selectAll: (selector: string, host?: HTMLElement) => HTMLElement[];
Parameters
| name | description | optional |
|---|---|---|
selector | CSS selector to locate elements | no |
host | Element to select elements from | yes (document.documentElement by default) |
Example
selectAll('meta'); // HTMLMetaElement[]
selectAll('div', body); // HTMLDivElement[]
selectOne
The selectOne function allows you to retrieve a DOM element by CSS selector. Its TypeScript signature is as follows:
declare const selectOne: (selector: string, host?: HTMLElement) => HTMLElement | null;
Parameters
| name | description | optional |
|---|---|---|
selector | CSS selector to locate element | no |
host | Element to select element from | yes (document.documentElement by default) |
Example
selectOne('meta'); // HTMLMetaElement
selectOne('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);
}
Namespacing
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
| name | description | optional |
|---|---|---|
suffix | Custom suffix for all generated keys | yes |
prefix | Custom prefix for all generated keys | yes (origin by default) |
Methods
| name | description |
|---|---|
key | Generate 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, by default, any possible conflict. Its TypeScript signature is as follows:
type Suffix = boolean | null | string;
declare class Store extends Namespace {
constructor(suffix?: Suffix);
set(key: string, value: any): void;
get(key: string): any | null;
remove(key: string): void;
}
Parameters
| name | description | optional |
|---|---|---|
suffix | Custom suffix for all generated keys, makes sharing storage easier | yes (pathName by default) |
If the value of the suffix parameter is true, the automatic prefixing of store keys will stop at the directory containing the current HTML file. This makes it easier to share the same store between different HTML files located at the same level of the same directory, without having to define a custom suffix.
Methods
| name | description |
|---|---|
get | Retrieve a previously stored value for a given key |
set | Store/overwrite a value for a given key |
remove | Delete 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;
change?: ChangeCallback;
submit: SubmitCallback;
};
type Suffix = boolean | null | string;
type FieldBuilder = (removeButton: HTMLButtonElement) => HTMLElement;
declare class Form extends Store {
constructor(host: HTMLFormElement, options: Options, suffix?: Suffix);
buildRemovableField(fieldBuilder: FieldBuilder, buttonText?: string): HTMLElement;
addRemovableFieldOnClick(clickHost: HTMLElement, addHost: HTMLElement, fieldBuilder: FieldBuilder, buttonText?: string): [ClickListener, CLickListener];
}
Parameters
| name | description | optional |
|---|---|---|
host | Form element to add behavior to | no |
options | Object describing the behavior to add to the form | no |
options.persisted | List of field names (name attribute) whose (valid) value must be persisted, or true for all | yes |
options.reset | Function to call after resetting the form if it has a reset button and the persisted option is used | yes |
options.change | Function to call when the values of the persisted fields change, if valid | yes |
options.submit | Function to call on form submission (the event.preventDefault method is called internally) | no |
suffix | Custom suffix for all generated keys, makes sharing storage easier | yes (pathName by default) |
Methods
| name | description |
|---|---|
buildRemovableField | Create a field that can be deleted by clicking a button |
addRemovableFieldOnClick | Add fields, which can be deleted, to a list by clicking on a given element |
The addRemovableFieldOnClick method calls buildRemovableField internally, our dock relies on it for example in its Settings tab. The clickHost element, passed as parameter, is automatically enabled.
The default delete button text is 'Remove' and the danger CSS class automatically is added to it.
The return value of this method is a tuple containing two instances of ClickListener, one for the addition listener attached to the clickHost element and the other for the removal listener attached to the addHost element.
The first child element of the one created via the fieldBuilder function passed as a parameter, carrying the required attribute, will automatically receive the focus.
Example
const formElement = document.getElementById('form');
const form = new Form(formElement, {
persisted: ['fieldA', 'fieldB'], // Pass `true` to persist all fields.
reset() {
console.log('reset');
},
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');
const [
additionClickListener, // instanceof ClickListener
removalClickListener // instanceof ClickListener
] = form.addRemovableFieldOnClick(addButton, fieldsList, itemBuilder, 'Delete');
additionClickListener.off();
removalClickListener.off();
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
| name | description | optional |
|---|---|---|
duration | Hold duration, expressed in seconds | yes (parameters.queueDuration by default) |
manual | Automatically react (false) or not (true) to pause and skip system events | yes (false by default) |
Methods
| name | description |
|---|---|
add | Add a new item to the queue |
pause | Pause or resume the execution of the queue |
skip | Directly go to the next item in the queue, has no effect when the queue is paused |
clear | Allows you to completely empty the queue |
dispose | Cleanup 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 |
The onStart and onEnd functions are respectively called when an element starts to exit the queue and after it has completely exited. The onEnd function is optional.
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
| name | description | optional |
|---|---|---|
threshold | Maximum number of accepted repetitions for the same action | yes (parameters.antiSpamThreshold by default) |
delta | Duration after which the same action will no longer be considered spam, expressed in seconds | yes (parameters.antiSpamDelta by default) |
Methods
| name | description |
|---|---|
check | Returns 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
| name | description | optional |
|---|---|---|
url | Address of the audio file to load | no |
volume | Audio file playback volume, between 0 and 1 | yes (parameters.volume by default) |
crossOrigin | Value to configure for the crossOrigin property | yes ('anonymous' by default) |
manual | Automatically react (false) or not (true) to mute system events | yes (false by default) |
Methods
| name | description |
|---|---|
stop | Completely stop playing the audio file |
mute | Mute (true) or unmute (false) the sound without stopping the playback of the audio file |
dispose | Cleanup 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 by creating dedicated emitters. Its TypeScript signature is as follows:
declare class CustomEvent {
emit(data?: any, otherProperties?: object): void;
toString(): string;
}
declare class Emitter {
constructor(crossOrigin?: boolean, namespace?: string);
[eventName: string]: CustomEvent;
}
Parameters
| name | description | optional |
|---|---|---|
crossOrigin | Indicates whether emitted events can be received by overlays of different origins (true) | yes (false by default) |
namespace | Adds a namespace to emitted events, recommended when crossOrigin is true | yes |
Example
const { customEvent } = new Emitter();
const props = { key: 'value' };
const data = { props };
customEvent.emit(); // Emitted event: { category: '<namespace>.customEvent' }
customEvent.emit(data); // Emitted event: { category: '<namespace>.customEvent', data }
customEvent.emit(data, props); // Emitted event: { category: '<namespace>.customEvent', data, ...props }
customEvent.emit(undefined, props); // Emitted event: { category: '<namespace>.customEvent', ...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
| name | description | optional |
|---|---|---|
events | Object listing the functions to call upon receipt of given events | no |
Example
const logger = type => data => console.log(type, data);
const { customEvent } = new Emitter();
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.
[customEvent]: logger(customEvent.toString())
});
observer.off();
observer.on();
OBS
obsAPI
The obsAPI object allows you to use the OBS JavaScript API by creating dedicated event emitters or retrieving the names of events to observe, the complete list of possibilities is available on this page. Its TypeScript signature is as follows:
declare class OBSEvent {
emit(...args: any[]): void;
toString(): string;
}
declare const obsAPI: { [eventName: string]: OBSEvent | string };
Example
const {
SceneChanged,
pluginVersion,
getCurrentScene,
setCurrentScene,
stopStreaming
} = obsAPI;
new Observer({
[SceneChanged]({ data }) {
// Do whatever you want with the data here.
// `data.name` contains the name of the new scene.
},
[pluginVersion]({ data }) {
// Do whatever you want with the value here.
},
[getCurrentScene]({ data }) {
// Do whatever you want with the value here.
}
});
// Getters.
pluginVersion.emit();
getCurrentScene.emit();
// Setters.
setCurrentScene.emit('new scene name');
stopStreaming.emit();
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
| name | description | optional |
|---|---|---|
url | Address of the stylesheet to load (local, remote, or data URL) | no |
crossOrigin | Value to configure for the crossOrigin property | yes ('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;
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
| name | description | optional |
|---|---|---|
query | Google 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.
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>
currentLang
The constant named currentLang corresponds to the value passed as the system parameter named lang; 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
| name | description | optional |
|---|---|---|
translations | Objects containing translation data, indexed by language | yes |
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'
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 currentLang; 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 thedata-i18nattribute 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.
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.