Application Programmer Interface (API)

The following are important global JavaScript functions you can call from your experiment.

submit(str, [callback])
After each player's move, you should call submit(str, callback) where str is a string (or XML or JSON) value corresponding to each player's move. If given, callback will be called with a JavaScript object of the response when the request finishes.
fetchMove(participant, round, index, callback)
Used to fetch a player's move for a round given a participant id, round number, move number within that round, and callback function. callback is called with the value of that player's move once the request returns.
getName(playerNum)
You can specify randomly assigned player names (gender specific) in the experiment configuration interface. This function gives you the player's assigned name. If you don't specify player names in the configuration, it will be Player 1,2, etc.
setRound(round)
Should be called with an integer every time the round changes. What defines a round is completely up to you. Typically there are several instruction or practice rounds.
Rounds are not required to be consecutive. We typically set our first "real" game round as round 101.
getFile(fileName)
Gets the full path to the latest version of the requested file. Useful for linking images or other external objects. Note that JavaScript and CSS files are automatically linked in each experiment.
getMatrixValue(matrix,row,column)
values in "matrix" in row, column. This is a shortcut to variables[matrix][row-1][column-1]
sendChat(val,to)
val is a string containing the message; to is a matrix containing the player numbers [1,2,4] etc; this will cause chatReceived(playerNum,val) to be called on everyone in the "to" array. You may want to include "myid" in the array if you want volunteer science to automatically call chatReceived(playerNum,val) locally.
Note that if you override
sendCom(val,com_type,to)
more abstract version of sendChat() used to send any kind of information to other players. com_type is user defined, but we use "-1" for chat.
writeScore(name, score, order, callback)
call this when the user has finished a game, we support multiple score types for each experiment. name is the type of score, score is how many points, order should be "high" or "low" to say whether a high score is good (like football) or a low score is good (like golf), callback is optional and should have the arguments (rank, count). Rank his how well the player did out of count players. So if the game has been played by 100 players, and the local player is the 77th best, then rank = 77, count = 100, so they are ranked 77 out of 100.
getTopScores(name, count, callback)
use this to request the top scorers for the award name, count is how many you want returned say 10 for top 10. callback should have 2 paramenters (count, scores); count is how many scores have been recorded, scores is the top XXX scores.
writeAward(name, val)
name is the name of your award, val is not necessary, but you may include specific details about this award.
HSVtoRGB(h, s, v)
handy function to convert colors
sendComBot(playerNum,val,com_type,to)
Used to send communication from bots or dropped players. Note that for security, this will fail if the human player is still active.
submitBot(playerNum, round, val, callback)
Call this to submit as a disconnected player or bot. Note that for security, this will fail if the human player is still active.
experimentComplete()
call this at the end of your experiment, to request the IRB consent form if the user hasn't already accepted it. The function is also a shortcut to the following calls:
  • disableQuitConfirm() -- if the user calls "quit" during the experiment, a popup discourages them from doing this. This function disables it.
  • enablePlayAgain() -- turns on the "Play Again" button.
  • enableSubmitFeedback() -- turns on the "Submit Feedback" button
payAMT(pay,bonus)
only needed for AMT-enabled experiments.
  • pay is true/false depending if they did a good enough job to be paid
  • bonus is in US Dollars and should be how much more they should be paid above the base pay.
Note this automatically calls experimentComplete(), and does no harm to call in non-amt mode.
assignQualification(name)
only needed for AMT-enabled experiments.
  • name is the name of your qualification
Example
assignQualification('demographic survey complete');
creates the qualification "demographic survey complete" in Mechanical Turk and assigns it to the worker
getUserData(callback, exp)
Get all data for the presently logged in user for a given experiment. Returns an array of all submits, ordered by date.
  • callback function to be called when data loads; accepts data array as argument
  • exp id of the experiment to load data for
log(string)
This is to help the developer debug problems. These are displayed to browser specific logs, such as "FireBug" in "Firefox"
1configureThanks(type, scoreName, scoreOrder, showRank, showPercentile)
Call this before experimentComplete() to change how the thank you page is displayed.
  • type is the one of "default", "award", or "score"
    • "default": shows the amount of money the user has saved for science by playing
    • "award": shows all awards the player earned during the game. Only visible awards with images earned during the test will be shown.
    • "score": shows the score as specified below
    • If you use the score version, you must specify an Object with the following parameters
      • name: is the name associated with the score (i.e. 'Total Points')
      • score: the score to give the user (i.e. 30)
      • order: specifies the order in which score will be sorted, "low" if low scores are better (i.e. golf), "high" if high scores are better (i.e. real sports)
      • show_rank (optional, default false): if true, rank relative to other players will be displayed
      • show_percentile (optional, default false): if true, score percentile (relative to other players) will be displayed
      Example: configureThanks("score", {"name": "points", "score": 30, "order": "high", "show_rank": true, "show_percentile": true})
2configureThanks(message, social_message optional)
Use this form of configureThanks to specify a custom message for the thank you page, instead of using one of the prescribed options. If specified, the second parameter will be used for the Facebook, Twitter, and Reddit messages. Otherwise, the message itself will be used.
getConsumables(class, set, amount, callback(data, err){} )
Request 1 or more consumables from Volunteer Science. "data" is a list of strings. You can configure/create classes/sets from your research page.
setConsumables(class, set, condition)
If / when the participant completes the consumable, then tell Volunteer Science that you used it. "condition" is a string from the list you received from getConsumables().
createSubject(email, phone, first_name, last_name, callback)
Add a subject with the specified contact details to the subject management system for the team associated with the experiment. Either email or phone (or both) must be specified. first_name and last_name are optional. The callback should accept the arguments (status, message). Status will be true if the subject was created successfully, and message may specify some additional information (i.e., that the subject is a duplicate). If the subject is not created successfully, status will be false and will be a string telling you what went wrong.
createSubjectInput(container, callback)
Call this to automatically generate an input form for collecting a participant's contact details. The form contains fields for the subject's phone number, email, first name, and last name. When the form is submitted, createSubject is called automatically. Specify an (optional) callback exactly like the one you'd define for createSubject.
vs_fbq(event, config)
To use this function, create an experiment variable called PIXEL_ID, and set it to your Facebook Pixel ID. Volunteer Science will automatically configure your Pixel for you. Then, call vs_fbq with the event you want to track, either standard or custom, and any parameters you wish to specify. As an example: vs_fbq("InitiateCheckout", {"value": 50});
For a complete list of Pixel events, click here.

The following JavaScript variables are set globally before initialize() is called:

myid
Current user's id (player 1 is "1")
numPlayers
Number of players in current game.
initialState
the value returned from buildInitialState() if you used this function; note, this is calculated on player 1's client, then delivered to the rest of the clients before calling initialize()
participants
JavaScript object consisting of a key of the user id and a value of a JavaScript object with the user's name. Note that both participant ids and indexes start with 1, not 0.
variables["variable-name"]
JavaScript object consisting of key value pairs of the variables you set in your experiment's back end.
getFile("file-name.ext")
Get a link to your file (for example an image file).
/attachment/<file.ext>
Alternative approach to getting a link to a file
seed
Use this as the random seed to generate random choices the same on all clients. See more in Best Practices
currentRound
Your current round, set by setRound()
activePlayers[playerNum]
Array of true/false for which players are still active. Use this to decide if this client should manage the bots: See more in Best Practices
awards[playerNum][awardName]
Count of how many times playerNum has received awardName.
score[playerNum][scoreName]
Table showing playerNum's score for scoreName.
DEVICE_TYPE
User's type of device: UNKNOWN = 0; DESKTOP = 1; TABLET = 2; SMART_PHONE = 3;
IS_AMT
true if this experiment is called from Amazon Mechanical Turk
IS_AMT_PREVIEW
true if this experiment is called from Amazon Mechanical Turk but is only a Preview (not yet paid). See the AMT docs for more information about preview mode.
IS_FACEBOOK
Set to true if the user is logged in with a Facebook account
SUPPRESS_THANKS
Set to true by default. If false, the "thank you page" will be displayed when experimentComplete() is called.

These are functions you should define in your experiment.

buildInitialState()
called on player 1, return an object that will be available in initialize()
initialize()
This function is called after the experiment page is done loading -- after the "initialState" variable is available. You should define this function and initialize your experiment in it.
newMove(participantId, index)
This function is called after the server detects any participant has made a new move. Index is the number of new moves that participant has made. You have to define this yourself!
Note that you are only notified of moves in your currentRound. If a different client is in a different round, you will not be notified until you setRound().
chatReceived(from, val, to_parts)
Called when someone sent a chat. From is an integer of the playerNum, val is the string/json, to_parts is an array of playerNum
comReceived(index, newCom)
You may need to send communications other than chat. This function is called on all clients, not just the ones who should receive the message. You must internally decide whether to deliver the communication to the local user.
index is a unique internal index for the communication.
newCom is an object with the following attributes:
  • .com_type -- integer of the communication type. This is defined by you, the application developer, though we internally use "-1" for chat.
  • .val -- string or other JSON object sent from sendCom()
  • .from -- playerNum who sent it
  • .to_parts -- array of player numbers that received it
Note, overriding comReceived() prevents chatReceived() from being automatically called. You should check if com_type == -1 and call chatReceived() if needed.
playerDisconnect(playerNum)
related: activePlayers[playerNum] = true/false
Implement this to detect if a player dropped out. See Best Practices for more details.

These are special variables you can define in your experiment.

next_experiment
The next_experiment variable allows you to chain studies together in a sequence. To create the next_experiment variable, you need to go into the study that will be sending participants to another study and in the "Manage Variables" tab, under "Add New Custom Variable" create a new variable called "next_experiment". Set that variable to the id number of the study you want to send them to (e.g. 123 for https://volunteerscience.com/experiments/join_category=123). You can change the next_experiment variable during your study by calling variables['next_experiment']=123 in your code.

Note also that jQuery and Bootstrap are included in every page.