Roll20 makes a number of functions available that are not part of core JavaScript or some other library.
Games may run Mod Script Sandbox v1.0 (Campaign().sandboxVersion === "1.0") or v1.5 ("1.5"). Features marked Mod Script Sandbox v1.5 only. do not work on v1.0.
Global variables
| Variable | Description |
|---|---|
_ |
This is the namespace object for the Underscore.js library. |
state |
Properties of the state object will persist between game sessions. |
_ (Underscore)
This is the namespace object for the Underscore.js library. Underscore has many functions for collection manipulation.
state
Properties of the state object will persist between game sessions. The same state object is also shared between all Mod Scripts in a campaign, so it is strongly recommended that when writing values to state, you minimize your footprint as much as possible in order to avoid name collisions. Note: state gets serialized with JSON, so you cannot store functions or objects with cyclical references.
Global Functions
| Return type | Function | Description |
|---|---|---|
| Roll20 object | Campaign |
Gets the singleton Campaign Roll20 object. |
| Roll20 object | createObj |
Creates a new Roll20 object. |
| Array of Roll20 objects | filterObjs |
Gets all Roll20 objects which pass a predicate test. |
| Array of Roll20 objects | findObjs |
Gets all Roll20 objects with properties that match a given set of attributes. |
| Array of Roll20 objects | getAllObjs |
Gets all Roll20 objects in the campaign. |
| varies | getAttrByName |
Gets the current or max value of an attribute Roll20 object. |
| varies | getComputed |
v1.5 only. Gets a Beacon computed property. |
| varies | getSheetDefaultValue |
Gets a character sheet default for an attribute name. |
| varies | getSheetItem |
Gets a sheet item (attribute; on v1.5 also Beacon / user.*). |
| Roll20 object | getObj |
Gets a specific Roll20 object. |
log |
Logs a message to the Mod Output Console. | |
on |
Registers an event handler. | |
onSheetWorkerCompleted |
Registers a one-time event handler to run after a full stack of Sheet Worker Scripts completes. | |
performAction |
v1.5 only. Performs a Beacon sheet action. | |
| Boolean | playerIsGM |
Checks whether a player currently has GM privileges. |
playJukeboxPlaylist |
Start playing a jukebox playlist. | |
| Number | randomInteger |
Generates a random integer value. |
sendChat |
Sends a chat message. | |
sendPing |
Sends a ping similar to holding the left mouse button. | |
setAttrs |
Sets one or more attributes on a character. | |
setComputed |
v1.5 only. Sets a writable Beacon computed property. | |
setSheetItem |
Sets a sheet item (attribute; on v1.5 also Beacon / user.*). |
|
spawnFx |
Spawns a particle emitter. | |
spawnFxBetweenPoints |
Spawns a particle emitter that moves from one point to another. | |
spawnFxWithDefinition |
Spawns a particle emitter that is not represented by an FX Roll20 object. | |
stopJukeboxPlaylist |
Stops all currently playing jukebox playlists. | |
toAbove |
v1.5 only. Places an object immediately above another on the same layer. | |
toBack |
Moves a graphic Roll20 object below all of the other graphics on the same tabletop layer. | |
toBelow |
v1.5 only. Places an object immediately below another on the same layer. | |
toFront |
Moves a graphic Roll20 object above all of the other graphics on the same tabletop layer. | |
| Card helpers |
shuffleDeck, cardInfo, recallCards, dealCardsToTurn, drawCard, pickUpCard, takeCardFromPlayer, playCardToTable, giveCardToPlayer — see Objects: Deck. |
Campaign
Parameters
No parameters
Returns
The singleton campaign Roll20 object.
Examples
var currentPageID = Campaign().get('playerpageid'),
currentPage = getObj('page', currentPageID);Campaign().sandboxVersion is "1.0" or "1.5". Campaign().nodeVersion is the Node.js version string. Mod Script Sandbox v1.5 only: sheetName, computedSummary, and actionSummary. See Objects: Campaign.
createObj
Parameters
TYPE (String) The type of Roll20 object to create. You may create 'graphic', 'text', 'path', 'pathv2', 'character', 'ability', 'attribute', 'handout', 'rollabletable', 'tableitem', 'macro', 'card', 'deck', 'custfx', 'window', 'door', and 'pin'. Mod Script Sandbox v1.5 only: 'pageFolder'.
ATTRIBUTES (Object) The initial values to use for the Roll20 object’s properties.
Returns
The Roll20 object that was created.
Examples
When creating a Roll20 object that has a parent object (such as creating an attribute Roll20 object, which is a child of a character Roll20 object), you must supply the id of the parent in attributes.
on('add:character', function(obj) {
createObj('attribute', {
name: 'Strength',
current: 0,
max: 30,
characterid: obj.id
});
});When creating a path Roll20 object, you must supply a value for the read-only property _path. This is an exception to the rule that prevents you from setting the value of read-only properties when creating Roll20 objects.
createObj('path', {
left: 7000,
top: 140,
width: 140,
height: 140,
layer: 'objects',
path: JSON.stringify([['M', 0, 0], ['L', 70, 0], ['L', 0, 70], ['L', 0, 0]])
});When creating a handout Roll20 object, you cannot set the text or gmnotes at the time of creation.
var handout = createObj('handout', {
name: 'A Letter Addressed to You',
inplayerjournals: 'all',
archived: false
});
handout.set({
notes: 'Notes can only be set after the handout is created',
gmnotes: 'GM Notes can only be set after the handout is created'
});filterObjs
Parameters
CALLBACK (Function) A predicate function to test all Roll20 objects against. The callback function receives a Roll20 object as a parameter, and should return either true (for Roll20 objects that will be included in the filterObjs return value) or false (for all other Roll20 objects).
Returns
An array of Roll20 objects which passed the predicate test.
findObjs
Parameters
ATTRIBUTES (Object) A collection of key:value pairs to match with Roll20 objects in the campaign.
OPTIONS (Object, optional)
-
caseInsensitive— if true, string comparisons are case-insensitive. -
startsWith— if true, string values match as a prefix. -
tagMatch— when matchingtags:'all'(default; object has every listed tag),'any'(at least one),'only'(exactly the listed set).
Returns
An array of Roll20 objects with properties that match attributes.
Examples
var npcs = findObjs({ type: 'character', controlledby: '' });
var knights = findObjs({ type: 'character', name: 'Sir' }, { startsWith: true });getAllObjs
Parameters
No parameters
Returns
An array of all Roll20 objects in the campaign.
getAttrByName
Parameters
CHARACTER_ID (String) The id of the character. ATTRIBUTE_NAME (String) The name of the attribute. VALUE_TYPE (String, optional) "current" or "max" (defaults to "current").
Returns
The current or max property. If not set, the character sheet default is used (if any).
getComputed
Mod Script Sandbox v1.5 only. (On v1.0 this name is a no-op stub.)
Parameters
An object: { characterId, property, args?, playerId? }.
When using a Beacon character sheet, gets the value of a computed property. List names with Campaign().computedSummary. playerId is optional; some Beacon features (for example roll queries) require it.
getSheetDefaultValue
Parameters
ATTRIBUTE_NAME (String), VALUE_TYPE (String, optional) "current" or "max".
Returns
The sheet default for that field, not the live character value.
getSheetItem
Parameters
getSheetItem(characterId, property, valtype?, options?) — asynchronous (Promise).
On v1.0 this wraps getAttrByName. Mod Script Sandbox v1.5 only: on Beacon sheets it also reads computed properties and custom attributes named user.*.
getObj
Parameters
TYPE (String), ID (String)
Returns
The specified Roll20 object.
on('chat:message', function(msg) {
var sendingPlayer = getObj('player', msg.playerid);
});log
Parameters
MESSAGE (varies) Posted to the Mod Output Console. Transformed with JSON.stringify.
Mod Script Sandbox v1.5 only. Error messages often include a context object such as [Roll20 character -id].
on
Parameters
EVENT (String) There are five types of event: ready, change, add, destroy, chat. With the exception of ready, all event types must also be paired with an object type. For chat, this is always message. For everything else, this is the type property of a Roll20 object. In addition to the object type, change events can also optionally specify a property of the specified Roll20 object to watch. The 2-3 parts of the event (type, object, and optionally property) are separated by colons. So, valid event strings include but are not limited to “ready”, “chat:message”, “change:graphic”, “change:campaign:playerpageid”, “add:character”, and “destroy:handout”.
CALLBACK (Function) ready events have no callback parameters. change events have an obj parameter (the Roll20 object after the change) and a prev parameter (a plain JavaScript object of properties prior to the change). add events have an obj parameter (the new object). destroy events have an obj parameter (the no-longer existing object). chat events have a msg parameter (details of the message).
Returns
(Void)
Events are fired in the order they were registered, and from most to least specific. In this example, a change to a graphic Roll20 object’s left property will result in function3 getting called, followed by function1 and then function2.
on('change:graphic', function1);
on('change:graphic', function2);
on('change:graphic:left', function3);add events will attempt to fire for Roll20 objects that are already in the campaign when a new session starts. In order to prevent this behavior, you can wait to register your add event until the ready event fires.
on('add:graphic', function(obj) {
// When the session begins, this function will be called for every graphic in the campaign
});
on('ready', function() {
on('add:graphic', function(obj) {
// This function will *only* be called when a new graphic Roll20 object is created
});
});The prev parameter for change events is not a Roll20 object. You cannot use get or set, and you cannot omit the leading underscores on read-only properties. Use prev._id, not prev.id.
For the async fields of character and handout Roll20 objects (notes, gmnotes, and bio), the prev parameter will not hold the data you need. Cache previous values yourself if required.
Do not change the chat message type string "api" in examples. Messages beginning with ! have type === "api".
onSheetWorkerCompleted
Parameters
CALLBACK (Function) Called when the current stack of Sheet Worker Scripts completes. Intended to be called prior to setWithWorker. Runs only once. The callback may receive { workersExecuted: boolean }.
performAction
Mod Script Sandbox v1.5 only. (On v1.0 this name is a no-op stub.)
Parameters
{ characterId, action, args?, playerId? }
Performs a Beacon sheet action. List names with Campaign().actionSummary. playerId is optional; some Beacon features require it. If the name is not a Beacon action, v1.5 may fall back to a character ability of that name via sendChat.
playerIsGM
Parameters
PLAYER_ID (String)
Returns
true if the player currently has GM permissions.
Especially useful for limiting Mod Script commands to GM use. Keep msg.type !== 'api' as written — that is the command-message type.
playJukeboxPlaylist
Parameters
PLAYLIST_ID (String) The id of the playlist to start playing.
randomInteger
Parameters
MAX (Number) Inclusive maximum.
Returns
A random integer between 1 and max. Prefer this over Math.random() for dice-like ranges.
sendChat Asynchronous
Parameters
SPEAKINGAS (String) A name, or player|player_id / character|character_id. MESSAGE (String). CALLBACK (Function, optional) — results are passed to the callback instead of appearing in chat. OPTIONS (Object, optional) noarchive, use3d.
See Mod Scripts: Chat for command buttons ([label](!command)).
sendPing
Parameters
LEFT, TOP, PAGE_ID, PLAYER_ID (optional), MOVEALL (optional), VISIBLETO (optional). If player_id is omitted, the ping is yellow. If moveAll is true, views center on the ping. visibleTo may be a player id, an array of ids, or a comma-delimited string.
setAttrs
Parameters
CHARACTER_ID (String), ATTRIBUTE_OBJ (Object of name → value). Names ending in _max set max. Repeating $n names are supported. options.silent uses set instead of setWithWorker.
setComputed
Mod Script Sandbox v1.5 only.
{ characterId, property, args?, playerId? } — sets a writable Beacon computed property. See Campaign().computedSummary.
setSheetItem
setSheetItem(characterId, property, value, valtype?, options?) — asynchronous. On v1.0 sets attributes. v1.5: also Beacon computed properties and user.* custom attributes. Options include createAttr, withWorker, allowThrow.
spawnFx
Parameters
LEFT (Number) The x-coordinate to place the particle emitter. TOP (Number) The y-coordinate. TYPE (String) For built-in effects, "type-color", where type is one of bomb, bubbling, burn, burst, explode, glow, missile, or nova and color is one of acid, blood, charm, death, fire, frost, holy, magic, slime, smoke, or water. For custom effects, the id of a custfx object. Note: beam, breath, and splatter cannot be used with spawnFx — see spawnFxBetweenPoints. PAGE_ID (String, optional) defaults to Campaign().get('playerpageid').
spawnFx(1400, 1400, 'bubbling-acid');
spawnFxBetweenPoints
Parameters
START (Object) { x, y }. END (Object) { x, y }. TYPE (String) as spawnFx, plus beam, breath, and splatter. PAGE_ID (String, optional).
spawnFxBetweenPoints({ x: 1400, y: 1400 }, { x: 2100, y: 2100 }, 'beam-acid');Mod Script Sandbox v1.5 only. Beam-type effects point directly at the end point (an angle calculation bug is corrected).
spawnFxWithDefinition
Parameters
LEFT, TOP, DEFINITION (Object describing the emitter), PAGE_ID (optional). See Custom FX on the Objects article for property names.
spawnFxWithDefinition(1400, 1400, {
maxParticles: 200,
size: 15,
sizeRandom: 3,
lifeSpan: 20,
lifeSpanRandom: 5,
speed: 7,
speedRandom: 2,
gravity: { x: 0.01, y: 0.65 },
angle: 270,
angleRandom: 35,
emissionRate: 1,
startColour: [0, 35, 10, 1],
startColourRandom: [0, 10, 10, 0.25],
endColour: [0, 75, 30, 0],
endColourRandom: [0, 20, 20, 0]
});stopJukeboxPlaylist
Stops all currently playing jukebox playlists.
stopJukeboxPlaylist();
Card helpers
Available on both sandbox versions. Full details are on Mod Scripts: Objects (Deck).
shuffleDeck(deckid, discard, newOrder)cardInfo(settings)recallCards(deckid, type)dealCardsToTurn(deckid)drawCard(deckid, cardid)pickUpCard(cardid, fromDiscard)takeCardFromPlayer(playerid, options)playCardToTable(cardid, settings)giveCardToPlayer(cardid, playerid)
toAbove
Mod Script Sandbox v1.5 only.
Parameters
OBJ (graphic, text, or path), TARGET (object or id).
Places obj immediately above target on the same layer.
toBack / toFront
OBJ must be a tabletop object (graphic, text, or path). On v1.5 these are substantially faster. Graphic, path, and text also have instance methods toFront() / toBack() on v1.5.
toBelow
Mod Script Sandbox v1.5 only.
Places obj immediately below target (object or id) on the same layer.