Stats APIs (getStatsAsync(), setStatsAsync() and incrementStatsAsync()) have been fully removed on September 28th, 2022.
postSessionScoreAsync
as a replacement as it will provide better info about user actions for dialogs invoked via this API.shareAsync
since it wasn't being used. We've also removed the IMMEDIATE_CLEAR strategy from updateAsync
as we have a policy in place to restrict custom updates to one per context session.Top level namespace for the Instant Games SDK.
Contains functions and properties related to the current player.
A unique identifier for the player. A Facebook user's player ID will remain constant, and is scoped to a specific game. This means that different games will have different player IDs for the same user. This function should not be called until FBInstant.initializeAsync() has resolved.
// This function should be called after FBInstant.initializeAsync() // resolves. var playerID = FBInstant.player.getID();
Returns string? A unique identifier for the player.
A unique identifier for the player. This is the standard Facebook Application-Scoped ID which is used for all Graph API calls. If your game shares an AppID with a native game this is the ID you will see in the native game too.
// This function should be called after FBInstant.initializeAsync() // resolves. var playerASID = FBInstant.player.getASIDAsync().then( asid => console.log(asid) );
Returns Promise<string?> A unique identifier for the player.
Fetch the player's unique identifier along with a signature that verifies that the identifier indeed comes from Facebook without being tampered with. This function should not be called until FBInstant.initializeAsync() has resolved.
requestPayload
string? A developer-specified payload to include
in the signed response.// This function should be called after FBInstant.initializeAsync() // resolves. FBInstant.player.getSignedPlayerInfoAsync('my_metadata') .then(function (result) { // The verification of the ID and signature should happen on server side. SendToMyServer( result.getPlayerID(), // same value as FBInstant.player.getID() result.getSignature(), 'GAIN_COINS', 100); });
Returns Promise<SignedPlayerInfo> A promise that resolves with a #signedplayerinfo object.
Returns a promise that resolves with whether the player can subscribe to the game bot or not.
// This function should be called before FBInstant.player.subscribeBotAsync() FBInstant.player.canSubscribeBotAsync().then( can_subscribe => console.log(can_subscribe) ); // 'true'
Returns Promise<boolean> Whether a player can subscribe to the game bot or not. Developer can only call subscribeBotAsync() after checking canSubscribeBotAsync(), and the game will only be able to show the player their bot subscription dialog once per week.
Request that the player subscribe the bot associated to the game. The API will reject if the subscription fails - else, the player will subscribe the game bot.
FBInstant.player.subscribeBotAsync().then( // Player is subscribed to the bot ).catch(function (e) { // Handle subscription failure });
Returns Promise A promise that resolves if player successfully subscribed to the game bot, or rejects if request failed or player chose to not subscribe.
The player's localized display name. This function should not be called until FBInstant.initializeAsync() has resolved.
// This function should be called after FBInstant.initializeAsync() // resolves. var playerName = FBInstant.player.getName();
Returns string? The player's localized display name.
A url to the player's public profile photo. The photo will always be a square, and with dimensions of at least 200x200. When rendering it in the game, the exact dimensions should never be assumed to be constant. It's recommended to always scale the image to a desired size before rendering. The value will always be null until FBInstant.initializeAsync() resolves.
WARNING: Due to CORS, using these photos in the game canvas can cause it to be tainted, which will prevent the canvas data from being extracted. To prevent this, set the cross-origin attribute of the images you use to 'anonymous'.
var playerImage = new Image(); playerImage.crossOrigin = 'anonymous'; // This function should be called after FBInstant.initializeAsync() // resolves. playerImage.src = FBInstant.player.getPhoto();
Returns string? Url to the player's public profile photo.
Retrieve data from the designated cloud storage of the current player. Please note that JSON objects stored as string values would be returned back as JSON objects.
FBInstant.player .getDataAsync(['achievements', 'currentLife']) .then(function(data) { console.log('data is loaded'); var achievements = data['achievements']; var currentLife = data['currentLife']; });
Returns Promise<Object> A promise that resolves with an object which contains the current key-value pairs for each key specified in the input array, if they exist.
Set data to be saved to the designated cloud storage of the current player. The game can store up to 1MB of data for each unique player.
data
Object An object containing a set of key-value pairs
that should be persisted to cloud storage. The object must contain
only serializable values - any non-serializable values will cause
the entire modification to be rejected.FBInstant.player .setDataAsync({ achievements: ['medal1', 'medal2', 'medal3'], currentLife: 300, }) .then(function() { console.log('data is set'); });
Returns Promise A promise that resolves when the input values are set. NOTE: The promise resolving does not necessarily mean that the input has already been persisted. Rather, it means that the data was valid and has been scheduled to be saved. It also guarantees that all values that were set are now available in player.getDataAsync.
Immediately flushes any changes to the player data to the designated cloud storage. This function is expensive, and should primarily be used for critical changes where persistence needs to be immediate and known by the game. Non-critical changes should rely on the platform to persist them in the background. NOTE: Calls to player.setDataAsync will be rejected while this function's result is pending.
FBInstant.player .setDataAsync({ achievements: ['medal1', 'medal2', 'medal3'], currentLife: 300, }) .then(FBInstant.player.flushDataAsync) .then(function() { console.log('Data persisted to FB!'); });
Returns Promise A promise that resolves when changes have been persisted successfully, and rejects if the save fails.
Fetches an array of ConnectedPlayer objects containing information about active players (people who played the game in the last 90 days) that are connected to the current player.
var connectedPlayers = FBInstant.player.getConnectedPlayersAsync() .then(function(players) { console.log(players.map(function(player) { return { id: player.getID(), name: player.getName(), } })); }); // [{id: '123456789', name: 'Paul Atreides'}, {id: '987654321', name: 'Duncan Idaho'}]
Returns Promise<Array<ConnectedPlayer>> A promise that resolves with a list of connected player objects. NOTE: This function should not be called until FBInstant.initializeAsync() has resolved.
Contains functions and properties related to the current game context.
A unique identifier for the current game context. This represents a specific context that the game is being played in (for example, a facebook post). The identifier will be null if game is being played in a solo context. This function should not be called until FBInstant.startGameAsync has resolved.
// This function should be called after FBInstant.initializeAsync() // resolves. var contextID = FBInstant.context.getID();
Returns string? A unique identifier for the current game context.
The type of the current game context. POST - A facebook post. THREAD - A chat thread. GROUP - A facebook group. SOLO - Default context, where the player is the only participant.
This function should not be called until FBInstant.startGameAsync has resolved.
// This function should be called after FBInstant.initializeAsync() // resolves. var contextType = FBInstant.context.getType();
Returns ("POST"
| "THREAD"
| "GROUP"
| "SOLO"
) Type of the current game context.
This function determines whether the number of participants in the current game context is between a given minimum and maximum, inclusive. If one of the bounds is null only the other bound will be checked against. It will always return the original result for the first call made in a context in a given game play session. Subsequent calls, regardless of arguments, will return the answer to the original query until a context change occurs and the query result is reset. This function should not be called until FBInstant.startGameAsync has resolved.
console.log(FBInstant.context.isSizeBetween(3, 5)); (Context size = 4) // {answer: true, minSize: 3, maxSize: 5}
console.log(FBInstant.context.isSizeBetween(5, 7)); (Context size = 4) // {answer: false, minSize: 5, maxSize: 7}
console.log(FBInstant.context.isSizeBetween(2, 10)); (Context size = 3) // {answer: true, minSize: 2, maxSize: 10} console.log(FBInstant.context.isSizeBetween(4, 8)); (Still in same context) // {answer: true, minSize: 2, maxSize: 10}
console.log(FBInstant.context.isSizeBetween(3, null)); (Context size = 4) // {answer: true, minSize: 3, maxSize: null}
console.log(FBInstant.context.isSizeBetween(null, 3)); (Context size = 4) // {answer: false, minSize: null, maxSize: 3}
console.log(FBInstant.context.isSizeBetween("test", 5)); (Context size = 4) // null
console.log(FBInstant.context.isSizeBetween(0, 100)); (Context size = null) // null
Returns (ContextSizeResponse | null)
Request a switch into a specific context. If the player does not have permission to enter that context, or if the player does not provide permission for the game to enter that context, this will reject. Otherwise, the promise will resolve when the game has switched into the specified context.
id
string ID of the desired context.console.log(FBInstant.context.getID()); // 1122334455 FBInstant.context .switchAsync('1234567890') .then(function() { console.log(FBInstant.context.getID()); // 1234567890 });
Returns Promise A promise that resolves when the game has switched into the specified context, or rejects otherwise.
Opens a context selection dialog for the player. If the player selects an available context, the client will attempt to switch into that context, and resolve if successful. Otherwise, if the player exits the menu or the client fails to switch into the new context, this function will reject.
options
Object? An object specifying conditions on the contexts
that should be offered.options.filters
Array<ContextFilter>? The set of filters to
apply to the context suggestions.options.maxSize
number? The maximum number of participants that
a suggested context should ideally have.options.minSize
number? The minimum number of participants that
a suggested context should ideally have.console.log(FBInstant.context.getID()); // 1122334455 FBInstant.context .chooseAsync() .then(function() { console.log(FBInstant.context.getID()); // 1234567890 });
console.log(FBInstant.context.getID()); // 1122334455 FBInstant.context .chooseAsync({ filters: ['NEW_CONTEXT_ONLY'], minSize: 3, }) .then(function() { console.log(FBInstant.context.getID()); // 1234567890 });
Returns Promise A promise that resolves when the game has switched into the context chosen by the user. Otherwise, the promise will reject (if the user cancels out of the dialog, for example).
Attempts to create a context between the current player and a specified player or a list of players. This API supports 3 use cases: 1) When the input is a single playerID, it attempts to create or switch into a context between a specified player and the current player 2) When the input is a list of connected playerIDs, it attempts to create a context containing all the players 3) When there's no input, a friend picker will be loaded to ask the player to create a context with friends to play with
For each of these cases, the returned promise will reject if any of the players listed are not Connected Players of the current player, or if the player denies the request to enter the new context. Otherwise, the promise will resolve when the game has switched into the new context.
suggestedPlayerIDs
(string | Array<string>)? null
(string | Array<String>) ?suggestedPlayerIDs A list of game suggested
playerIDs or a single suggested playerID or no inputconsole.log(FBInstant.context.getID()); // 1122334455 FBInstant.context .createAsync('12345678') .then(function() { console.log(FBInstant.context.getID()); // 5544332211 });
console.log(FBInstant.context.getID()); // 1122334455 FBInstant.context .createAsync(['12345678', '87654321']) .then(function() { console.log(FBInstant.context.getID()); // 55443322112232 });
console.log(FBInstant.context.getID()); // 1122334455 FBInstant.context .createAsync() .then(function() { console.log(FBInstant.context.getID()); // 55443322112232 });
Returns Promise A promise that resolves when the game has switched into the new context, or rejects otherwise.
Gets an array of #contextplayer objects containing information about active players in the current context (people who played the game in the current context in the last 90 days). This may include the current player.
var contextPlayers = FBInstant.context.getPlayersAsync() .then(function(players) { console.log(players.map(function(player) { return { id: player.getID(), name: player.getName(), } })); }); // [{id: '123456789', name: 'Luke'}, {id: '987654321', name: 'Leia'}]
Returns Promise<Array<ContextPlayer>>
Contains functions and properties related to payments and purchases of game products.
Fetches the game's product catalog.
FBInstant.payments.getCatalogAsync().then(function (catalog) { console.log(catalog); // [{productID: '12345', ...}, ...] });
Returns Promise<Array<Product>> The set of products that are registered to the game.
Begins the purchase flow for a specific product. Will immediately reject if called before FBInstant.startGameAsync() has resolved.
purchaseConfig
PurchaseConfig The purchase's configuration details.FBInstant.payments.purchaseAsync({ productID: '12345', developerPayload: 'foobar', }).then(function (purchase) { console.log(purchase); // {productID: '12345', purchaseToken: '54321', developerPayload: 'foobar', ...} });
Returns Promise<Purchase> A Promise that resolves when the product is successfully purchased by the player. Otherwise, it rejects.
Fetches all of the player's unconsumed purchases. The game must fetch the current player's purchases as soon as the client indicates that it is ready to perform payments-related operations, i.e. at game start. The game can then process and consume any purchases that are waiting to be consumed.
FBInstant.payments.getPurchasesAsync().then(function (purchases) { console.log(purchase); // [{productID: '12345', ...}, ...] });
Returns Promise<Array<Purchase>> The set of purchases that the player has made for the game.
Consumes a specific purchase belonging to the current player. Before provisioning a product's effects to the player, the game should request the consumption of the purchased product. Once the purchase is successfully consumed, the game should immediately provide the player with the effects of their purchase.
purchaseToken
string The purchase token of the purchase that should
be consumed.FBInstant.payments.consumePurchaseAsync('54321').then(function () { // Purchase successfully consumed! // Game should now provision the product to the player });
Returns Promise A Promise that resolves when the purchase has been consumed successfully.
Sets a callback to be triggered when Payments operations are available.
callback
Function The callback function to be executed when Payments
are available.FBInstant.payments.onReady(function () { console.log('Payments Ready!') });
Returns void
Contains functions and properties related to instant tournaments.
Posts a player's score to Facebook. This API should only be called within a tournament context at the end of an activity (example: when the player doesn't have "lives" to continue the game). This API will be rate-limited when called too frequently. Scores posted using this API should be consistent and comparable across game sessions. For example, if Player A achieves 200 points in a session, and Player B achieves 320 points in a session, those two scores should be generated from activities where the scores are fair to be compared and ranked against each other.
score
number An integer value representing the player's score at
the end of an activity.function onScore(score) { if (score > bestScore) { bestScore = score; FBInstant.tournament.postScoreAsync(bestScore) .then(function() { ... }); } }
Returns Promise A promise that resolves when the score post is completed.
Opens the tournament creation dialog if the player is not currently in a tournament session
payload
CreateTournamentPayload
Throws INVALID_PARAM
Returns Promise<Tournaments.Tournament>
Opens the reshare tournament dialog if the player is currently in a tournament session
payload
ShareTournamentPayload Specifies share content. See example for
details.FBInstant.tournament.shareAsync({ score: 3, data: { myReplayData: '...' } }).then(function() { // continue with the game. });
Returns Promise A promise that resolves if the tournament is shared, or rejects otherwise.
Request a switch into a specific tournament context. If the player is not a participant of the tournament, or there are not any connected players participating in the tournament, this will reject. Otherwise, the promise will resolve when the game has switched into the specified context.
FBInstant.getTournamentAsync().then((tournament) => { console.log(tournament.getID()); }); // 1122334455 FBInstant.tournament .joinAsync('1122334455') .then(function() { // Context switch completed successfully. });
Returns Promise A promise that resolves when the game has switched into the specified tournament context, or rejects otherwise.
Returns a list of eligible tournaments that can be surfaced in-game, including tournaments 1) the player has created; 2) the player is participating in; 3) the player's friends (who granted permission) are participating in. The instant tournaments returned are active. An instant tournament is expired if its end time is in the past. For each instant tournament, there is only one unique context ID linked to it, and that ID doesn't change.
FBInstant.tournament.getTournamentsAsync() .then(tournaments => { // tournament list });
Returns Promise<Array<Tournaments.Tournament>>
Contains functions and properties related to Graph APIs
Performs a graph API Call and returns the result.
path
string The graph API path to perform the request against.method
string? HTTP method that will be used for this request. GET
is the default if not specified.params
Object? Parameters that will be sent as part of the request.FBInstant.graphApi.requestAsync('/me?fields=id,name') .then(function(response) { ... });
Returns Promise<Object> the result of the graph API call.
[IN CLOSED BETA] Contains functions and properties related to arenas.
[IN CLOSED BETA]
Brings up a dialog showing Arena details and prompting the user to register for the Arena if the user is not registered to it already. If the user click on 'Register', they become registered to the Arena, but if the user dimisses the dialog, USER_INPUT error will be thrown
FBInstant.arenas.getArenasAsync() .then(function(arenas) { arenas.forEach(arena => arena.registerAsync().then(...)); });
Returns Promise
[IN CLOSED BETA]
Fetches the all the NOT_STARTED and RUNNING arenas that belong to the game.
FBInstant.arenas.getArenasAsync() .then(function(arenas) { arenas.forEach(arena => console.log(arena.getID())); });
[IN CLOSED BETA] Contains functions and properties related to gaming squads.
[IN CLOSED BETA]
Brings up a dialog for the player to join a Squad if they are not part of it. If the user accepts, they become part of the squad thread and the game context switches into the squad. If they are part of the Squad already, the dialog will prompt the user to switch into the Squad context.
payload
JoinGamingSquadPayload? FBInstant.squads.getAsync(squadID) .then(function(squad) { squad.joinAsync().then(...) });
Returns Promise
[IN CLOSED BETA]
Brings up a dialog for the player to confirm if they want to leave the Squad. If the player confirms, they are removed from the Squad and the messenger thread that is associated with this Squad.
payload
LeaveGamingSquadPayload? FBInstant.squads.getAsync(squadID) .then(function(squad) { squad.leaveAsync().then(...) });
Returns Promise
[IN CLOSED BETA]
Brings up a dialog for the player to add their friends to the current squad.
payload
AddToGamingSquadPayload? FBInstant.squads.getAsync(squadID) .then(function(squad) { squad.addToSquadAsync().then(...) });
Returns Promise
[IN CLOSED BETA]
Brings up a dialog for the player to create a Squad. If the player creates the Squad, the promise will resolve with the new Squad instance and the game session will be switched into this newly created Squad context. The promise will reject if the player closes the dialog instead
payload
CreateGamingSquadPayload? FBInstant.squads.createAsync() .then(function(squad) { ... });
Returns Promise<GamingSquad>
[IN CLOSED BETA]
Fetch an existing Squad. If the Squad does not exist, or the player cannot interact with the Squad, this API will reject with the GAMING_SQUAD_NOT_FOUND error code.
id
string The squad ID or context IDFBInstant.squads.getAsync(squadID) .then(function(squad) { console.log(squad.getID()) });
Returns Promise<GamingSquad>
[IN CLOSED BETA]
Fetches the current player's existing squads, if any.
FBInstant.squads.getPlayerSquadsAsync() .then(function(squads) { squads.forEach(squad => console.log(squad.getID())); });
Returns Promise<Array<GamingSquad>>
[IN CLOSED BETA]
Fetches the current player's existing squads, if any.
FBInstant.squads.canUseSquadsAsync() .then(function(isEligible) { if (isEligible) { FBInstant.squads.getAsync(squadID) .then(function(squad) { console.log(squad.getID()) }); } });
Returns Promise<boolean> Returns whether the current user is eligible to use squads
[IN CLOSED BETA] Contains functions and properties related to gaming community.
[IN CLOSED BETA]
Check if user can get live streams
FBInstant.community.canGetLiveStreamsAsync() .then(function(data) { console.log(data); });
Returns Promise<boolean> Returns bool for whether user/game can get live streams
[IN CLOSED BETA]
Check if user can follow official game page
FBInstant.community.canFollowOfficialPageAsync() .then(function(data) { console.log(data); });
Returns Promise<boolean> Returns bool for whether user can follow official game page
[IN CLOSED BETA]
Check if user can join official game group
FBInstant.community.canJoinOfficialGroupAsync() .then(function(data) { console.log(data); });
Returns Promise<boolean> Returns bool for whether user can join official game group
[IN CLOSED BETA]
Fetch list of live streams tagged with the current game.
req
LiveStreamsRequest FBInstant.community.getLiveStreamsAsync({maxCount:1}) .then(function(liveStreams) { console.log(liveStreams); });
Returns Promise<[LiveStream]>
[IN CLOSED BETA]
Renders overlay with grid of live streams
FBInstant.community.liveStreamsOverlayAsync()
Returns Promise
[IN CLOSED BETA]
Renders overlay with follow official page CTA
FBInstant.community.followOfficialPageAsync()
Returns Promise
[IN CLOSED BETA]
Renders overlay with join group CTA
FBInstant.community.joinOfficialGroupAsync()
Returns Promise
[IN CLOSED BETA] Contains functions and properties related to interactive streams.
[IN CLOSED BETA]
Creates a video player embedded in the game. The video player can play a live stream or offline video based on the video ID specified.
videoID
string ID of the video to be played.initialState
VideoPlayerInstanceState Initial state of the video.
Optional. Defaults value is { mute: false, show: true, play: true,
loop: false } with the video covering the entire instant games container.FBInstant.videoPlayer.createAsync(videoID) .then(function(videoPlayerInstance) { console.log(videoPlayerInstance.getCurrentTimestamp()); });
Returns Promise<VideoPlayerInstance>
[IN CLOSED BETA] Contains functions and properties related to the messenger rooms environment.
[IN CLOSED BETA]
Shows the AR effect for the user in the room session. If the user has a non-game effect applied, it will prompt the user for permission for the first time. If the user denis, the promise is rejected, otherwise it is resolved after applying the effect
FBInstant.room.loadCameraEffectAsync() .then(function(effect) { effect.showAsync().then(() => console.log("Effect shown")); });
Returns Promise Resolves when the effect is applied to the player
[IN CLOSED BETA]
Retrieves the current real-time match for the gameplay environment, if one exists.
FBInstant.room.getCurrentMatchAsync() .then(function(match) { ... });
[IN CLOSED BETA]
Retrieves and loads a specified AR effect that has been registered for the game
cameraEffectArgs
CameraEffectArgs The args representing the effect to be loaded. See example for detailsFBInstant.room.loadCameraEffectAsync({effectID: '123'}) .then(function(effect) { ... });
Returns Promise<CameraEffect>
[IN CLOSED BETA]
Clears the current AR effect in the rooms call. If an effect is present that was not applied by the game, the player will be prompted to approve the removal of the effect. The API will resolve after the effect is cleared, or will reject if the user denies the effect removal.
FBInstant.room.clearCameraEffectAsync() .then(function() { ... });
Returns Promise Resolves if the effect is cleared
The current locale. See https://lookaside.facebook.com/developers/resources/?id=FacebookLocales.xml for a complete list of supported locale values. Use this to determine what languages the current game should be localized with. The value will not be accurate until FBInstant.initializeAsync() resolves.
// This function should be called after FBInstant.initializeAsync() // resolves. var locale = FBInstant.getLocale(); // 'en_US'
Returns string The current locale.
The platform on which the game is currently running. The value will always be null until FBInstant.initializeAsync() resolves.
// This function should be called after FBInstant.initializeAsync() // resolves. var platform = FBInstant.getPlatform(); // 'IOS'
Returns (Platform | null)
The string representation of this SDK version.
// This function should be called after FBInstant.initializeAsync() // resolves. var sdkVersion = FBInstant.getSDKVersion(); // '2.0'
Returns string The SDK version.
Initializes the SDK library. This should be called before any other SDK functions.
FBInstant.initializeAsync().then(function() { // Many properties will be null until the initialization completes. // This is a good place to fetch them: var locale = FBInstant.getLocale(); // 'en_US' var platform = FBInstant.getPlatform(); // 'IOS' var sdkVersion = FBInstant.getSDKVersion(); // '3.0' var playerID = FBInstant.player.getID(); });
Returns Promise A promise that resolves when the SDK is ready to use.
Report the game's initial loading progress.
percentage
number A number between 0 and 100.FBInstant.setLoadingProgress(50); // Assets are 50% loaded
Returns void
Provides a list of API functions that are supported by the client.
// This function should be called after FBInstant.initializeAsync() // resolves. FBInstant.getSupportedAPIs(); // ['getLocale', 'initializeAsync', 'player.getID', 'context.getType', ...]
Returns Array<string> List of API functions that the client explicitly supports.
Returns any data object associated with the entry point that the game was launched from.
The contents of the object are developer-defined, and can occur from entry points on different platforms. This will return null for older mobile clients, as well as when there is no data associated with the particular entry point.
This function should be called after FBInstant.initializeAsync() resolves.
// This function should be called after FBInstant.initializeAsync() // resolves. const entryPointData = FBInstant.getEntryPointData();
Returns Object? Data associated with the current entry point.
Returns the entry point that the game was launched from.
This function should not be called until FBInstant.startGameAsync has resolved.
// This function should be called after FBInstant.initializeAsync() // resolves. FBInstant.getEntryPointAsync().then(entrypoint => console.log(entrypoint)); // 'admin_message'
Returns string The name of the entry point from which the user started the game
Sets the data associated with the individual gameplay session for the current context.
This function should be called whenever the game would like to update the current session data. This session data may be used to populate a variety of payloads, such as game play webhooks.
sessionData
Object An arbitrary data object, which must be less
than or equal to 1000 characters when stringified.FBInstant.setSessionData({coinsEarned: 10, eventsSeen: ['start', ...]});
Returns void
This indicates that the game has finished initial loading and is ready to start. Context information will be up-to-date when the returned promise resolves.
FBInstant.startGameAsync().then(function() { myGame.start(); });
Returns Promise A promise that resolves when the game should start.
[IN CLOSED BETA] Contains functions and properties related to in-game achievements.
[IN CLOSED BETA] Returns an ID of the Facebook video which launched this game.
FBInstant.getEntryPointVideoID() .then(function(videoID) { console.log('User entered game from video ' + videoID); });
Returns string? The video ID or null.
This invokes a dialog to let the user invite one or more people to the game. A blob of data can be attached to the share which every game session launched from the invite will be able to access from FBInstant.getEntryPointData(). This data must be less than or equal to 1000 characters when stringified. The user may choose to cancel the action and close the dialog, and the returned promise will resolve when the dialog is closed regardless if the user actually invited people or not.
payload
InvitePayload Specify what to share. See example for
details.FBInstant.inviteAsync({ image: base64Picture, text: { default: 'X is asking for your help!', localizations: { en_US: 'X is asking for your help!', es_LA: '\u00A1X pide tu ayuda!', } }, data: { myReplayData: '...' } }).then(function() { // continue with the game. });
Returns Promise A promise that resolves when the share is completed or cancelled.
This invokes a dialog to let the user share specified content, as a post on the user's timeline, for example. A blob of data can be attached to the share which every game session launched from the share will be able to access from FBInstant.getEntryPointData(). This data must be less than or equal to 1000 characters when stringified. The user may choose to cancel the share action and close the dialog, and the returned promise will resolve when the dialog is closed regardless if the user actually shared the content or not.
payload
SharePayload Specify what to share. See example for
details.FBInstant.shareAsync({ image: base64Picture, text: 'X is asking for your help!', data: { myReplayData: '...' }, switchContext: false, }).then(function() { // continue with the game. });
Returns Promise A promise that resolves when the share is completed or cancelled.
Informs Facebook of an update that occurred in the game. This will temporarily yield control to Facebook and Facebook will decide what to do based on what the update is. The returned promise will resolve/reject when Facebook returns control to the game.
payload
UpdatePayload A payload that describes the update.// This will post a custom update. When people launch the game from this // message, those game sessions will be able to access the specified blob // of data through FBInstant.getEntryPointData(). FBInstant.updateAsync({ action: 'CUSTOM', cta: 'Join The Fight', image: base64Picture, text: { default: 'X just invaded Y\'s village!', localizations: { ar_AR: 'X \u0641\u0642\u0637 \u063A\u0632\u062A ' + '\u0642\u0631\u064A\u0629 Y!', en_US: 'X just invaded Y\'s village!', es_LA: '\u00A1X acaba de invadir el pueblo de Y!', } } template: 'VILLAGE_INVASION', data: { myReplayData: '...' }, strategy: 'IMMEDIATE', notification: 'NO_PUSH', }).then(function() { // closes the game after the update is posted. FBInstant.quit(); });
Returns Promise A promise that resolves when Facebook gives control back to the game.
Request that the client switch to a different Instant Game. The API will reject if the switch fails - else, the client will load the new game.
appID
string The Application ID of the Instant Game to switch to.
The application must be an Instant Game, and must belong to the same
business as the current game. To associate different games with the same
business, you can use Business Manager:
https://developers.facebook.com/docs/apps/business-manager#update-business.data
Object? An optional data payload. This will be set as the
entrypoint data for the game being switched to. Must be less than or
equal to 1000 characters when stringified.FBInstant.switchGameAsync('12345678').catch(function (e) { // Handle game change failure });
FBInstant.switchGameAsync( '12345678', {referrer: 'game_switch', reward_coins: 30}, ).catch(function (e) { // Handle game change failure });
Returns Promise
Utility function to check if the current player can call switchNativeGameAsync()
Returns Promise<boolean> if the player can call switchNativeGameAsync
Request that the client switch to its Native (Android/iOS) Game. The API will reject if the switch fails - else, the client will open the Game or Store.
data
Object? An optional data payload. This will be set as the
entrypoint data for the game being switched to. Must be less than or
equal to 1000 characters when stringified.Returns Promise
Returns whether or not the user is eligible to have shortcut creation requested.
Will return false if createShortcutAsync was already called this session or the user is ineligible for shortcut creation.
FBInstant.canCreateShortcutAsync() .then(function(canCreateShortcut) { if (canCreateShortcut) { FBInstant.createShortcutAsync() .then(function() { // Shortcut created }) .catch(function() { // Shortcut not created }); } });
Returns Promise<boolean> Promise that resolves with true if the game can request the player create a shortcut to the game, and false otherwise
Prompts the user to create a shortcut to the game if they are eligible to Can only be called once per session. (see canCreateShortcutAsync)
FBInstant.canCreateShortcutAsync() .then(function(canCreateShortcut) { if (canCreateShortcut) { FBInstant.createShortcutAsync() .then(function() { // Shortcut created }) .catch(function() { // Shortcut not created }); } });
Returns Promise
Quits the game.
FBInstant.quit();
Returns void
Log an app event with FB Analytics. See https://developers.facebook.com/docs/javascript/reference/v2.8#app_events for more details about FB Analytics.
eventName
string Name of the event. Must be 2 to 40 characters,
and can only contain '_', '-', ' ', and alphanumeric characters.valueToSum
number An optional numeric value that FB Analytics can
calculate a sum with.parameters
Object An optional object that can contain up to
25 key-value pairs to be logged with the event. Keys must be 2 to 40
characters, and can only contain '_', '-', ' ', and alphanumeric
characters. Values must be less than 100 characters in length.var logged = FBInstant.logEvent( 'my_custom_event', 42, {custom_property: 'custom_value'} );
Returns APIError? The error if the event failed to log; otherwise returns null.
Set a callback to be fired when a pause event is triggered.
func
Function A function to call when a pause event occurs.FBInstant.onPause(function() { console.log('Pause event was triggered!'); pauseGameplay(); })
Returns void
Attempt to load or re-load a banner ad.
placementID
string The placement ID that's been set up in your
Audience Network settings.bannerPosition
string An optional parameter that sets the position of the banner to be "top" or "bottom." The default is a banner at the bottom of the screen.FBInstant.loadBannerAdAsync( 'my_placement_id' ).then(() => { console.log('success'); });
FBInstant.loadBannerAdAsync( 'my_placement_id', 'top' ).then(() => { console.log('success'); });
Returns Promise A promise that resolves after loading a banner ad, or rejects with a #apierror if it couldn't be created.
Attempt to hide a banner ad.
FBInstant.hideBannerAdAsync();
Returns Promise A promise that resolves after the ad is hidden.
Attempt to create an instance of interstitial ad. This instance can then be preloaded and presented.
placementID
string The placement ID that's been setup in your
Audience Network settings.FBInstant.getInterstitialAdAsync( 'my_placement_id' ).then(function(interstitial) { interstitial.getPlacementID(); // 'my_placement_id' });
Returns Promise A promise that resolves with a #adinstance, or rejects with a #apierror if it couldn't be created.
Attempt to create an instance of rewarded video. This instance can then be preloaded and presented.
placementID
string The placement ID that's been setup in your
Audience Network settings.FBInstant.getRewardedVideoAsync( 'my_placement_id' ).then(function(rewardedVideo) { rewardedVideo.getPlacementID(); // 'my_placement_id' });
Returns Promise A promise that resolves with a #adinstance, or rejects with a #apierror if it couldn't be created.
Attempt to create an instance of rewarded interstitial. This instance can then be preloaded and presented.
placementID
string The placement ID that's been setup in your
Audience Network settings.FBInstant.getRewardedInterstitialAsync( 'my_placement_id' ).then(function(rewardedInterstitial) { rewardedInterstitial.getPlacementID(); // 'my_placement_id' });
Returns Promise A promise that resolves with a #adinstance, or rejects with a #apierror if it couldn't be created.
Attempts to match the current player with other users looking for people to play with. There are two matching mechanisms: 1. Synchronous (realtime) match: Matches the current player with other users looking for people to play with. If successful, a new Messenger group thread will be created containing the matched players and the player will be switched into that thread's context. This will resolve when the player has successfully switched into the newly matched context. 2. Asynchronous (offline) match: Player starting an offline match will be added to a group thread right away. Players can leave the game while waiting more players to join. Once matched with other players, the player will be switched into the matched thread's context. This will resolve when the player has been successfully added to the group thread and switched into the matched context.
The default minimum and maximum number of players in one matched thread are 2 and 20 respectively, depending on how many players are trying to get matched around the same time. The values can be changed in fbapp-config.json. See the [Bundle Config documentation]https://developers.facebook.com/docs/games/instant-games/bundle-config for documentation about fbapp-config.json.
matchTag
string? Optional extra information about the player used
to group them with similar players. Players will only be grouped with
other players with exactly the same tag. The tag must only include
letters, numbers, and underscores and be 100 characters or less in
length.switchContextWhenMatched
boolean Optional extra parameter that
specifies whether the player should be immediately switched to the new
context when a match is found. By default this will be false which will
mean the player needs explicitly press play after being matched to
switch to the new context.offlineMatch
boolean Optional extra parameter that specifies
whether to start a match asynchronously. By default this will be false which
means the game will start a match synchronously.FBInstant .matchPlayerAsync('level1') .then(function() { console.log(FBInstant.context.getID()); // 12345 });
FBInstant .matchPlayerAsync() .then(function() { console.log(FBInstant.context.getID()); // 3456 });
FBInstant .matchPlayerAsync(null, true) .then(function() { console.log(FBInstant.context.getID()); // 3456 });
Returns Promise A promise that resolves when the player has been added to a group thread and switched into the thread's context.
Checks if the current player is eligible for the matchPlayerAsync API.
FBInstant .checkCanPlayerMatchAsync() .then(canMatch => { if (canMatch) { FBInstant.matchPlayerAsync('level1'); } });
Returns Promise<boolean> A promise that resolves with true if the player is eligible to match with other players and false otherwise.
Fetch a specific leaderboard belonging to this Instant Game.
name
string The name of the leaderboard. Each leaderboard for an
Instant Game must have its own distinct name.FBInstant.getLeaderboardAsync('my_awesome_leaderboard') .then(leaderboard => { console.log(leaderboard.getName()); // 'my_awesome_leaderboard' });
Returns Promise<Leaderboard> A promise that resolves with the matching leaderboard, rejecting if one is not found.
Posts a player's score to Facebook and resolves when score has been posted. This API should only be called at the end of an activity (example: when the player doesn't have "lives" to continue the game). This API will be rate-limited when called too frequently. Scores posted using this API should be consistent and comparable across game sessions. For example, if Player A achieves 200 points in a session, and Player B achieves 320 points in a session, those two scores should be generated from activities where the scores are fair to be compared and ranked against each other.
score
number An integer value representing the player's score at
the end of an activity.function onScore(score) { if (score > bestSessionScore) { bestSessionScore = score; FBInstant.postSessionScoreAsync(bestSessionScore) .then(() => { ... }); } }
Returns Promise A promise that resolves when all platform behavior (such as dialogs) generated from the posted score has completed, and the game should resume. If the behavior resulted in a social context change, that will be reflected by the time the Promise resolves.
Fetch the instant tournament out of the current context the user is playing. This will reject if there is no instant tournament link to the current context. The instant tournament returned can be either active or expired (An instant tournament is expired if its end time is in the past). For each instant tournament, there is only one unique context ID linked to it, and that ID doesn't change.
FBInstant.getTournamentAsync() .then(function(tournament) { console.log(tournament.getContextID()); console.log(tournament.getEndTime()); });
Returns Promise<Tournament>
Requests and performs haptic feedback on supported devices.
FBInstant.performHapticFeedbackAsync();
Returns Promise haptic feedback requested successfully
Represents a mapping from locales to translations of a given string. Each property is an optional five-character Facebook locale code of the form xx_XX. See https://lookaside.facebook.com/developers/resources/?id=FacebookLocales.xml for a complete list of supported locale codes.
Type: Object
Represents information about a player who is connected to the current player.
player
PlayerData Get the id of the connected player.
Returns string The ID of the connected player
Get the player's display name.
Returns string? The player's display name
Get the player's public profile photo.
Returns string? A url to the player's public profile photo
The answer field is true if the current context size is between the minSize and maxSize values that are specified in the object, and false otherwise.
Type: {answer: boolean, minSize: number?, maxSize: number?}
The layer in which the video will be rendered, relative to the game.
Type: ("BACK"
| "FRONT"
)
BACK
string The video layer behind the game layerFRONT
string The video layer in front of the game layerAn API Error returned by the Instant Games SDK
args
APIErrorArgs The relevant error code
Type: ErrorCodeType
A message describing the error
Type: string
Represents information about the player along with a signature to verify that it indeed comes from Facebook.
data
SignedPlayerInfoData Get the id of the player.
FBInstant.player.getSignedPlayerInfoAsync() .then(function (result) { result.getPlayerID(); // same value as FBInstant.player.getID() });
Returns string The ID of the player
A signature to verify this object indeed comes from Facebook. The string is base64url encoded and signed with an HMAC version of your App Secret, based on the OAuth 2.0 spec.
You can validate it with the following 4 steps:
Signature validation should only happen on your server. Never do it on the client side as it will compromise your app secret key.
FBInstant.player.getSignedPlayerInfoAsync() .then(function (result) { result.getSignature(); // Eii6e636mz5J47sfqAYEK40jYAwoFqi3x5bxHkPG4Q4.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImlzc3VlZF9hdCI6MTUwMDM5ODY3NSwicGxheWVyX2lkIjoiMTI0OTUyNTMwMTc1MjIwMSIsInJlcXVlc3RfcGF5bG9hZCI6Im15X2ZpcnN0X3JlcXVlc3QifQ });
Returns string The signature string.
Represents information about a player who is in the context that the current player is playing in.
player
PlayerData Get the id of the context player.
Returns string The ID of the context player
Get the player's localized display name.
Returns string? The player's localized display name.
Get the player's public profile photo.
Returns string? A url to the player's public profile photo
Represents a game's product information.
Type: Object
title
string The title of the productproductID
string The product's game-specified identifierdescription
string? The product descriptionimageURI
string? A link to the product's associated imageprice
string The price of the productpriceCurrencyCode
string The currency code for the productpriceAmount
number The numeric price of a productAn instant game tournament.
args
TournamentArgs The unique ID that is associated with this instant tournament.
FBInstant.getTournamentAsync() .then(function(tournament) { console.log(tournament.getID()); });
Returns string
The unique context ID that is associated with this instant tournament.
FBInstant.getTournamentAsync() .then(function(tournament) { console.log(tournament.getContextID()); });
Returns string
Timestamp when the instant tournament ends. If the end time is in the past, then the instant tournament is already finished and has expired.
FBInstant.getTournamentAsync() .then(function(tournament) { console.log(tournament.getEndTime()); });
Returns number
Title of the tournament provided upon the creation of the tournament. This is an optional field that can be set by creating the tournament using the FBInstant.tournament.createAsync() API.
Returns null if none was provided.
FBInstant.getTournamentAsync() .then(function(tournament) { console.log(tournament.getTitle()); })
Returns string?
Payload of the tournament provided upon the creation of the tournament. This is an optional field that can be set by creating the tournament using the FBInstant.tournament.createAsync() API.
Returns null if none was provided.
FBInstant.getTournamentAsync() .then(function(tournament) { console.log(tournament.getPayload()); })
Returns string?
Represents a tournament bracket
args
ArenaArgs [IN CLOSED BETA]
Returns string
[IN CLOSED BETA]
Returns string
[IN CLOSED BETA]
Returns number
[IN CLOSED BETA]
Returns string
[IN CLOSED BETA]
Returns number
[IN CLOSED BETA]
Returns the context ID of the match the player is in for this arena
Returns string?
Represents arguments to be sent to load an AR effect in Messenger Rooms.
Type: Object
effectID
string The ID of the effect to be loaded that is registered with the gameRepresentation of a group of players playing together in a messenger thread
args
GamingSquadArgs [IN CLOSED BETA]
The unique gaming squad ID.
FBInstant.squads.getAsync(contextID) .then(function(squad) { console.log(squad.getID()); });
Returns string The gaming squad ID
[IN CLOSED BETA]
The gaming squad name.
FBInstant.squads.getAsync(contextID) .then(function(squad) { console.log(squad.getName()); });
Returns string The name of the squad
[IN CLOSED BETA]
The URI for the gaming squad image.
FBInstant.squads.getAsync(contextID) .then(function(squad) { console.log(squad.getImage()); });
Returns string URI for gaming squad image
[IN CLOSED BETA]
The unique context ID that is associated with this gaming squad.
FBInstant.squads.getAsync(id) .then(function(squad) { console.log(squad.getContextID()); });
Returns string The context ID for this gaming squad
Represents an instance of an ad.
data
AdInstanceData type
AdType Return the Audience Network placement ID of this ad instance.
Returns string
Preload the ad. The returned promise resolves when the preload completes, and rejects if it failed.
FBInstant.getInterstitialAdAsync( 'my_placement_id', ).then(function(interstitial) { return interstitial.loadAsync(); }).then(function() { // Ad loaded });
Returns Promise
Present the ad. The returned promise resolves when user finished watching the ad, and rejects if it failed to present or was closed during the ad.
var ad = null; FBInstant.getRewardedVideoAsync( 'my_placement_id', ).then(function(rewardedVideo) { ad = rewardedVideo; return ad.loadAsync(); }).then(function() { // Ad loaded return ad.showAsync(); }).then(function() { // Ad watched });
Returns Promise
Live Match status that may be returned by the Instant Games API
Type: string
PENDING
string Match hasn't started yetRUNNING
string Match has begun and is runningCONCLUDED
string Match has been ended explicitlyABANDONED
string All the participants in the call have left the matchFBInstant.getCurrentMatchAsync() .then(function(match) { match.getStatusAsync().then(status => console.log(status)); });
Fetch the dynamic SDK configuration value for a given top-level key. We prioritize the result for the current SDK version, falling back to the default config value otherwise. If no value is present for either config, this function returns null.
NOTE: Remember, these values are dynamic and subject to change - make sure that the SDK code accessing them does not enforce any assumptions about their content, and that all accesses are resilient to unexpected types (in other words, accessors should only index into values after confirming their type and presence, and ensure safe fallback behavior for unexpected results). A poorly handled config access could cause the SDK to throw an exception, taking down games across the entire platform. Be careful!
key
string Returns (any | null)
A Live stream.
args
LiveStreamParams [IN CLOSED BETA]
Get live stream name
Returns string
[IN CLOSED BETA]
Get live stream concurrent viewer count
Returns number
[IN CLOSED BETA]
Get video thumbnail URL
Returns string?
[IN CLOSED BETA]
Get author name
Returns string
[IN CLOSED BETA]
Get author picture URL
Returns string?
[IN CLOSED BETA]
Get custom payload
Returns string?
[IN CLOSED BETA]
Open video player overlay
Returns Promise
Represents information about a player who is a participant in a real-time match.
player
PlayerData [IN CLOSED BETA]
Get the id of the live match player.
Returns string The ID of the live match player
[IN CLOSED BETA]
Get the player's display name.
Returns string? The player's display name
[IN CLOSED BETA]
Get the player's public profile photo.
Returns string? A url to the player's public profile photo
An Instant Games live match status, one of #livematchstatus
Type: string
A filter that may be applied to a Context Choose operation. This filter can now be used in Web and Mobile interfaces (Android and iOS).
NEW_CONTEXT_ONLY
: Prefer to only surface contexts the game has not been
played in before.INCLUDE_EXISTING_CHALLENGES
: Include the "Existing Challenges" section,
which surfaces actively played-in contexts that the player is a part of.NEW_PLAYERS_ONLY
: In sections containing individuals, prefer people who
have not played the game.Type: ("NEW_CONTEXT_ONLY"
| "INCLUDE_EXISTING_CHALLENGES"
| "NEW_PLAYERS_ONLY"
)
Represents the state of a video player instance.
Type: Object
mute
boolean? Mute or unmute the video. Optional and defaults to
false.show
boolean? Show or hide the video. This does not affect sound.
Optional and defaults to true.play
boolean? Play or pause the video. Optional and defaults to
true.loop
boolean? Specify whether to loop the video or not. Optional
and defaults to false.x
number? X position of the video in device pixels. This starts
at the left edge of the screen and grows to the right. Optional and
defaults to 0.y
number? Y position of the video in device pixels. This starts
at the top edge of the screen and grows to the bottom. Optional and
defaults to 0.width
number? Width of the video in device pixels. Optional and
defaults to cover full screen.height
number? Height of the video in device pixels. Optional and
defaults to cover full screen.placement
VideoPlayerPlacement? The layer in which the video will
be instantiated. Optional and defaults to application specification. If
application supports both layers, defaults to BACK.An Instant Game leaderboard
args
LeaderboardArgs The name of the leaderboard.
FBInstant.getLeaderboardAsync('my_leaderboard') .then(function(leaderboard) { console.log(leaderboard.getName()); // my_leaderboard });
Returns string
The ID of the context that the leaderboard is associated with, or null if the leaderboard is not tied to a particular context.
FBInstant.getLeaderboardAsync('contextual_leaderboard') .then(function(leaderboard) { console.log(leaderboard.getContextID()); // 12345678 });
FBInstant.getLeaderboardAsync('global_leaderboard') .then(function(leaderboard) { console.log(leaderboard.getContextID()); // null });
Returns (string | null)
Fetches the total number of player entries in the leaderboard.
FBInstant.getLeaderboardAsync('my_leaderboard') .then(function(leaderboard) { return leaderboard.getEntryCountAsync(); }) .then(function(count) { console.log(count); }); // 24
Returns Promise<number> A unique identifier for the player.
Updates the player's score. If the player has an existing score, the old score will only be replaced if the new score is better than it. NOTE: If the leaderboard is associated with a specific context, the game must be in that context to set a score for the player.
score
number The new score for the player. Must be a 64-bit
integer number.extraData
string Metadata to associate with the stored score.
Must be less than 2KB in size. (optional, default null
)FBInstant.getLeaderboardAsync('my_leaderboard') .then(function(leaderboard) { return leaderboard.setScoreAsync(42, '{race: "elf", level: 3}'); }) .then(function(entry) { console.log(entry.getScore()); // 42 console.log(entry.getExtraData()); // '{race: "elf", level: 3}' });
Returns Promise<LeaderboardEntry> Resolves with the current leaderboard entry for the player after the update.
Retrieves the leaderboard's entry for the current player, or null if the player has not set one yet.
FBInstant.getLeaderboardAsync('my_leaderboard') .then(function(leaderboard) { return leaderboard.getPlayerEntryAsync(); }) .then(function(entry) { console.log(entry.getRank()); // 2 console.log(entry.getScore()); // 42 console.log(entry.getExtraData()); // '{race: "elf", level: 3}' });
Returns Promise<LeaderboardEntry>? Resolves with the current leaderboard entry for the player.
Retrieves a set of leaderboard entries, ordered by score ranking in the leaderboard.
count
number The number of entries to attempt to fetch from the
leaderboard. Defaults to 10 if not specified. Currently, up to a maximum
of 100 entries may be fetched per query.offset
number The offset from the top of the leaderboard that
entries will be fetched from.FBInstant.getLeaderboardAsync('my_leaderboard') .then(function(leaderboard) { return leaderboard.getEntriesAsync(); }) .then(function(entries) { console.log(entries.length); // 10 console.log(entries[0].getRank()); // 1 console.log(entries[0].getScore()); // 42 console.log(entries[1].getRank()); // 2 console.log(entries[1].getScore()); // 40 });
FBInstant.getLeaderboardAsync('my_leaderboard') .then(function(leaderboard) { return leaderboard.getEntriesAsync(5, 3); }) .then(function(entries) { console.log(entries.length); // 5 console.log(entries[0].getRank()); // 4 console.log(entries[0].getScore()); // 34 console.log(entries[1].getRank()); // 5 console.log(entries[1].getScore()); // 31 });
Returns Promise<Array<LeaderboardEntry>> Resolves with the leaderboard entries that match the query.
Retrieves the leaderboard score entries of the current player's connected players (including the current player), ordered by local rank within the set of connected players.
count
number The number of entries to attempt to fetch from the
leaderboard. Defaults to 10 if not specified. Currently, up to a maximum
of 100 entries may be fetched per query.offset
number The offset from the set of ordered connected player
score entries to fetch from.FBInstant.getLeaderboardAsync('my_leaderboard') .then(function(leaderboard) { return leaderboard.getConnectedPlayerEntriesAsync(); }) .then(function(entries) { console.log(entries.length); // 10 console.log(entries[0].getRank()); // 1 console.log(entries[0].getScore()); // 42 console.log(entries[1].getRank()); // 2 console.log(entries[1].getScore()); // 40 });
FBInstant.getLeaderboardAsync('my_leaderboard') .then(function(leaderboard) { return leaderboard.getConnectedPlayerEntriesAsync(5, 3); }) .then(function(entries) { console.log(entries.length); // 5 console.log(entries[0].getRank()); // 4 console.log(entries[0].getScore()); // 34 console.log(entries[1].getRank()); // 5 console.log(entries[1].getScore()); // 31 });
Returns Promise<Array<LeaderboardEntry>> Resolves with the leaderboard entries that match the query.
Represents an individual purchase of a game product.
Type: Object
developerPayload
string? A developer-specified string, provided
during the purchase of the productpaymentActionType
string The current status of the purchase, such
as 'charge' or 'refund'paymentID
string The identifier for the purchase transactionproductID
string The product's game-specified identifierpurchasePrice
string Contains the local amount and currency
associated with the purchased itempurchaseTime
string Unix timestamp of when the purchase occurredpurchaseToken
string A token representing the purchase that may
be used to consume the purchasesignedRequest
SignedPurchaseRequest Server-signed encoding of the purchase
requestRepresents the current platform that the user is playing on.
Type: ("IOS"
| "ANDROID"
| "WEB"
| "MOBILE_WEB"
)
Represents an instance of an embedded video player.
data
VideoPlayerInstanceData [IN CLOSED BETA]
Return the ID of the video.
Returns string
[IN CLOSED BETA]
Get the current state of the video player instance.
Returns Promise<VideoPlayerInstanceState>
Update the state of the video player instance.
state
VideoPlayerInstanceState All fields are optional and only
the properties that are included in this object will be updated.Returns void
[IN CLOSED BETA]
Destroy the video player instance.
Returns void
[IN CLOSED BETA]
Return the number of milliseconds elapsed since the beginning of the video.
Returns number
[IN CLOSED BETA]
Make the video jump to the specified timestamp.
timestamp
number Milliseconds elapsed since the beginning of the video.Returns void
Represents content to be shared in invites sent by the user.
Type: Object
image
string A base64 encoded image to be shared.text
(string | LocalizableContent) A text message, or an object
with the default text as the value of 'default' and another object
mapping locale keys to translations as the value of 'localizations'.data
Object? A blob of data to attach to the share. All game
sessions launched from the share will be able to access this blob through
FBInstant.getEntryPointData().An instant game live match that is played in a Messenger Rooms call simultaneously by all the participants.
args
LiveMatchArgs [IN CLOSED BETA]
The unique live match ID.
FBInstant.room.getCurrentMatchAsync() .then(function(match) { console.log(match.getID()); });
Returns string The live match ID
[IN CLOSED BETA]
The unique context ID that is associated with this live match.
FBInstant.room.getCurrentMatchAsync() .then(function(match) { console.log(match.getContextID()); });
Returns string The context ID for this live match
[IN CLOSED BETA]
The current status of the live match, for example: PENDING, ABANDONED, CONCLUDED, RUNNING.
FBInstant.room.getCurrentMatchAsync() .then(function(match) { match.getStatusAsync().then(status => console.log(status)); });
Returns Promise<LiveMatchStatusType> The status of the live match
[IN CLOSED BETA]
Retrieves a list of players currently active in the match.
FBInstant.room.getCurrentMatchAsync() .then(function(match) { match.getActiveParticipantsAsync().then(activeParticipants => GameMatch.updatePlayers(activeParticipants)) });
Returns Promise<Array<LiveMatchPlayer>>
Error codes that may be returned by the Instant Games API
Type: string
ADS_FREQUENT_LOAD
string Ads are being loaded too frequently.ADS_NO_FILL
string We were not able to serve ads to the current
user. This can happen if the user has opted out of interest-based ads on
their device, or if we do not have ad inventory to show for that user.ADS_NOT_LOADED
string Attempted to show an ad that has not
been loaded successfully.ADS_TOO_MANY_INSTANCES
string There are too many concurrent
ad instances. Load and show existing ad instances before creating new ones.ANALYTICS_POST_EXCEPTION
string The analytics API experienced a
problem while attempting to post an event.CLIENT_REQUIRES_UPDATE
string [Deprecated] - The client requires
an update to access the feature that returned this result. If this result
is returned on web, it means the feature is not supported by the web client
yet. Deprecated in favor of CLIENT_UNSUPPORTED_OPERATION in v5.0 and aboveCLIENT_UNSUPPORTED_OPERATION
string The client does not support
the current operation. This may be due to lack of support on the client
version or platform, or because the operation is not allowed for the game
or player.INVALID_OPERATION
string The requested operation is invalid
or the current game state. This may include requests that violate
limitations, such as exceeding storage thresholds, or are not available in
a certain state, such as making a context-specific request in a solo
context.INVALID_PARAM
string The parameter(s) passed to the API are
invalid. Could indicate an incorrect type, invalid number of arguments, or
a semantic issue (for example, passing an unserializable object to a
serializing function).LEADERBOARD_NOT_FOUND
string No leaderboard with the requested
name was found. Either the leaderboard does not exist yet, or the name
did not match any registered leaderboard configuration for the game.LEADERBOARD_WRONG_CONTEXT
string Attempted to write to a
leaderboard that's associated with a context other than the one the game is
currently being played in.NETWORK_FAILURE
string The client experienced an issue with a
network request. This is likely due to a transient issue, such as the
player's internet connection dropping.PAYMENTS_NOT_INITIALIZED
string The client has not completed
setting up payments or is not accepting payments API calls.PENDING_REQUEST
string Represents a rejection due an existing
request that conflicts with this one. For example, we will reject any calls
that would surface a Facebook UI when another request that depends on a
Facebook UI is pending.RATE_LIMITED
string Some APIs or operations are being called
too often. This is likely due to the game calling a particular API an
excessive amount of times in a very short period. Reducing the rate of
requests should cause this error to go away.SAME_CONTEXT
string The game attempted to perform a context
switch into the current context.UNKNOWN
string An unknown or unspecified issue occurred. This
is the default error code returned when the client does not specify a code.USER_INPUT
string The user made a choice that resulted in a
rejection. For example, if the game calls up the Context Switch dialog and
the player closes it, this error code will be included in the promise
rejection.FBInstant.startGameAsync().catch(function(e) { console.log(e); }); // {code: 'CLIENT_UNSUPPORTED_OPERATION', message: '...'}
Represents the configurations used in creating an Instant Tournament
Type: Object
title
string? Optional text title for the tournamentimage
string? Optional base64 encoded image that will be
associated with the tournament and included in posts sharing the tournamentsortOrder
string? Optional input for the ordering of which score
is best in the tournament. The options are 'HIGHER_IS_BETTER' or
'LOWER_IS_BETTER'. If not specified, the default is 'HIGHER_IS_BETTER'.scoreFormat
string? Optional input for the formatting of the
scores in the tournament leaderboard. The options are 'NUMERIC' or 'TIME'.
If not specified, the default is 'NUMERIC'.endTime
number? Optional input for setting a custom end time
for the tournament. The number passed in represents a unix timestamp.
If not specified, the tournament will end one week after creation.An Instant Games error code, one of #errorcode
Type: string
Represents content to be shared by the user.
Type: Object
intent
("INVITE"
| "REQUEST"
| "CHALLENGE"
| "SHARE"
) Indicates the intent of the share.image
string A base64 encoded image to be shared.media
MediaParams? Optional content for the gif or video.text
string A text message to be shared.data
Object? A blob of data to attach to the share. All game
sessions launched from the share will be able to access this blob through
FBInstant.getEntryPointData().switchContext
boolean? A flag indicating whether to switch the user
into the new context created on sharingType: string
Eii6e636mz5J47sfqAYEK40jYAwoFqi3x5bxHkPG4Q4.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImlzc3VlZF9hdCI6MTUwMDM5ODY3NSwicGxheWVyX2lkIjoiMTI0OTUyNTMwMTc1MjIwMSIsInJlcXVlc3RfcGF5bG9hZCI6Im15X2ZpcnN0X3JlcXVlc3QifQ
Represents a custom link to be shared by the user.
Type: Object
image
string? A base64 encoded image to be shown for the link preview. The image is recommended to either be a square or of the aspect ratio 1.91:1text
string? A text description for the link preview. Recommended to be less than 44 charactersdata
Object A blob of data to associate with the shared link. All game
sessions launched from the share will be able to access this blob through
FBInstant.getEntryPointData().The configuration of a purchase request for a product registered to the game.
Type: Object
productID
string The identifier of the product to purchasedeveloperPayload
string? An optional developer-specified
payload, to be included in the returned purchase's signed request.Specify how we could get the content for the media.
Type: {url: string}
Represents the media payload used by custom update and custom share.
Type: {gif: MediaContent?, video: MediaContent?}
Optional
MediaContent , if provided, the content should contain
information for us to get the gif.Optional
MediaContent , if provided, the content should contain
information for us to get the video.gif
MediaContent? video
MediaContent? Represents the type of the update action to perform.
Type: string
CUSTOM
string A custom update, with all content specified by
the game.LEADERBOARD
string An update associated with an Instant Game
leaderboard.Represents an AR effect object that can be shown in a Messenger Rooms call.
args
CameraEffectArgs [IN CLOSED BETA]
The unique camera effect ID.
FBInstant.room.loadCameraEffectAsync() .then(function(effect) { console.log(effect.getID()); });
Returns string The camera effect ID
Represents a custom update for FBInstant.updateAsync. Note that if localized content is not provided, a Facebook supplied localized string will be used for the call to action and text.
The default
string should always be in English.
Type: Object
action
UpdateAction For custom updates, this should be 'CUSTOM'.template
string ID of the template this custom update is using.
Templates should be predefined in fbapp-config.json. See
the [Bundle Config documentation]https://developers.facebook.com/docs/games/instant-games/bundle-config for
documentation about fbapp-config.json.cta
(string? | LocalizableContent?) Optional call-to-action button
text. By default we will use a localized 'Play' as the button text.
To provide localized versions of your own call to action, pass an object
with the default cta as the value of 'default' and another object
mapping locale keys to translations as the value of 'localizations'.image
string? Optional data URL of a base64 encoded image.media
MediaParams? Optional content for the gif or
video. At least one image or media should be provided in order to render
the update.text
(string | LocalizableContent) A text message, or an object
with the default text as the value of 'default' and another object
mapping locale keys to translations as the value of 'localizations'.data
Object? A blob of data to attach to the update. All game
sessions launched from the update will be able to access this blob through
FBInstant.getEntryPointData(). Must be less than or equal to 1000
characters when stringified.strategy
string? Specifies how the update should be
delivered. This can be one of the following:
'IMMEDIATE' - The update should be posted immediately.
'LAST' - The update should be posted when the game session ends. The most
recent update sent using the 'LAST' strategy will be the one sent.
If no strategy is specified, we default to 'IMMEDIATE'.notification
string? Specifies notification setting for the
custom update. This can be 'NO_PUSH' or 'PUSH', and defaults to 'NO_PUSH'.
Use push notification only for updates that are high-signal and immediately
actionable for the recipients. Also note that push notification is not
always guaranteed, depending on user setting and platform policies.Represents a leaderboard update for FBInstant.updateAsync.
Type: Object
action
UpdateAction For a leaderboard update, this should be
'LEADERBOARD'.
text. By default we will use a localized 'Play Now' as the button text.name
string The name of the leaderboard to feature
in the update.text
string? Optional text message. If not specified, a
localized fallback message will be provided instead.Represents a string with localizations and a default value to fall back on.
Type: Object
default
string The default value of the string to use if
the viewer's locale is not a key in the localizations object.localizations
LocalizationsDict Specifies what string to use
for viewers in each locale.
See https://lookaside.facebook.com/developers/resources/?id=FacebookLocales.xml
for a complete list of supported locale values.Type: (CustomUpdatePayload | LeaderboardUpdatePayload)
Represents content used to reshare an Instant Tournament.
Type: Object
score
number An integer value representing the player's
latest score.data
Object? A blob of data to attach to the update.
Must be less than or equal to 1000 characters when stringified.Represents parameters used to configure a Gaming Squad
Type: Object
name
string An optional prefill for the squad name input in the creation dialog.
The player ultimately has control over the actual name.image
string Optional base64 encoded image that will be
associated with the gaming squad and will show up in the creation dialog. It will be the profile icon for the Messenger threadsquadTerm
string Optional localized term to use in place of 'Squad' in the dialog.Represents parameters used to configure the Join dialog
Type: Object
squadTerm
string Optional localized term to use in place of 'Squad' in the dialog.Represents parameters used to configure the Leave dialog
Type: Object
squadTerm
string Optional localized term to use in place of 'Squad' in the dialog.Represents parameters used to configure the Add to Squad dialog
Type: Object
squadTerm
string Optional localized term to use in place of 'Squad' in the dialog.A score entry for an Instant Game leaderboard
args
{rank: number, score: number, format_score: string, ts: number, extra_data: string?, player: {name: string, photo: string, player_id: string}} Gets the score associated with the entry.
leaderboard.setScoreAsync(9001) .then(function(entry) { console.log(entry.getScore()); // 9001 });
Returns number Returns an integer score value.
Gets the score associated with the entry, formatted with the score format associated with the leaderboard.
leaderboard.setScoreAsync(9001) .then(function(entry) { console.log(entry.getFormattedScore()); // '90.01 meters' });
Returns string Returns a formatted score.
Gets the timestamp of when the leaderboard entry was last updated.
leaderboard.setScoreAsync(9001) .then(function(entry) { console.log(entry.getTimestamp()); // 1515806355 });
Returns number Returns a Unix timestamp.
Gets the rank of the player's score in the leaderboard.
leaderboard.setScoreAsync(9001) .then(function(entry) { console.log(entry.getRank()); // 2 });
Returns number Returns the entry's leaderboard ranking.
Gets the developer-specified payload associated with the score, or null if one was not set.
leaderboard.setScoreAsync(42, '{race: "elf", level: 3}'); .then(function(entry) { console.log(entry.getExtraData()); // '{race: "elf", level: 3}' });
Returns string? An optional developer-specified payload associated with the score.
Gets information about the player associated with the entry.
leaderboard.setScoreAsync(9001) .then(function(entry) { console.log(entry.getPlayer().getName()); // Sally });
Returns LeaderboardPlayer
Details about the player associated with a score entry.
Gets the player's localized display name.
leaderboard.setScoreAsync(9001) .then(function(entry) { console.log(entry.getPlayer().getName()); // Sally });
Returns string The player's localized display name.
Returns a url to the player's public profile photo.
leaderboard.setScoreAsync(9001) .then(function(entry) { console.log(entry.getPlayer().getPhoto()); // <photo_url> });
Returns string? Url to the player's public profile photo.
Gets the game's unique identifier for the player.
leaderboard.setScoreAsync(9001) .then(function(entry) { console.log(entry.getPlayer().getID()); // 12345678 });
Returns string? The game-scoped identifier for the player.