API Reference 8.0 {#api-reference-8.0}


Changelog

1. FBInstant.overlayViews New module added for creation and management of overlay view iFrames to be used for Zero Permissions.
2. Removal of profile pictures and names APIs APIs returning profile pictures, names of current player or their friends have been removed to fit the Zero Permissions model. You can use overlay views to render this information instead.

FBInstant

Top level namespace for the Instant Games SDK.


community

Contains functions and properties related to gaming community.


Properties

  • canFollowOfficialPageAsync function (): [Promise][1]<[boolean][2]> Check if user can follow official game page
  • canJoinOfficialGroupAsync function (): [Promise][1]<[boolean][2]> Check if user can join official game group
  • followOfficialPageAsync function (): [Promise][1] Renders overlay with follow official page CTA
  • joinOfficialGroupAsync function (): [Promise][1] Renders overlay with join group CTA

canFollowOfficialPageAsync( )

Check if user can follow official game page


Examples
FBInstant.community.canFollowOfficialPageAsync()
    .then(function(data) {
        console.log(data);
    });
  • Throws INVALID_OPERATION

Returns [Promise][1]<[boolean][2]> Returns bool for whether user can follow official game page


canJoinOfficialGroupAsync( )

Check if user can join official game group


Examples
FBInstant.community.canJoinOfficialGroupAsync()
    .then(function(data) {
        console.log(data);
    });
  • Throws INVALID_OPERATION

Returns [Promise][1]<[boolean][2]> Returns bool for whether user can join official game group


followOfficialPageAsync( )

Renders overlay with follow official page CTA


Examples
FBInstant.community.followOfficialPageAsync()
  • Throws NETWORK_FAILURE
  • Throws INVALID_OPERATION
  • Throws PAGE_NOT_LINKED

Returns [Promise][1]


joinOfficialGroupAsync( )

Renders overlay with join group CTA


Examples
FBInstant.community.joinOfficialGroupAsync()
  • Throws NETWORK_FAILURE
  • Throws INVALID_OPERATION
  • Throws GROUP_NOT_LINKED

Returns [Promise][1]


tournament

Contains functions and properties related to instant tournaments.


Properties

  • createAsync function ([CreateTournamentPayload][3]): [Promise][1]<[Tournament][4]> Opens the tournament creation dialog
  • getTournamentsAsync function (): [Promise][1]<[Array][5]<[Tournament][4]>> Returns a list of eligible tournaments
  • joinAsync function ([string][6]): [Promise][1] Request a switch into a specific tournament context
  • postScoreAsync function ([number][7]): [Promise][1]<[boolean][2]> Posts a player's score to the tournament
  • shareAsync function ([ShareTournamentPayload][8]): [Promise][1] Opens the reshare tournament dialog

postScoreAsync( )

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.


Parameters
  • score [number][7] An integer value representing the player's score at the end of an activity.

Examples
function onScore(score) {
    if (score > bestScore) {
        bestScore = score;
        FBInstant.tournament.postScoreAsync(bestScore)
            .then(function() {
                ...
            });
    }
}
  • Throws INVALID_PARAM
  • Throws TOURNAMENT_NOT_FOUND
  • Throws NETWORK_FAILURE

Returns [Promise][1] A promise that resolves when the score post is completed.


createAsync( )

Opens the tournament creation dialog if the player is not currently in a tournament session


Parameters
  • payload [CreateTournamentPayload][3] Specifies the payload for the creation of the tournament

  • Throws INVALID_PARAM

  • Throws INVALID_OPERATION
  • Throws DUPLICATE_POST
  • Throws NETWORK_FAILURE
  • Throws OPERATION_SUPPRESSED

Returns [Promise][1]<[Tournament][4]> A promise that resolves if the tournament creation is a success, or rejects otherwise


shareAsync( )

Opens the reshare tournament dialog if the player is currently in a tournament session


Parameters
  • payload [ShareTournamentPayload][8] Specifies share content. See example for details.

Examples
FBInstant.tournament.shareAsync({
    score: 3,
    data: { myReplayData: '...' }
}).then(function() {
    // continue with the game.
});
  • Throws INVALID_OPERATION
  • Throws TOURNAMENT_NOT_FOUND
  • Throws NETWORK_FAILURE

Returns [Promise][1] A promise that resolves if the tournament is shared, or rejects otherwise.


joinAsync( )

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.


Parameters
  • tournamentID [string][6] The Tournament ID of the desired context to switch into.

Examples
FBInstant.getTournamentAsync().then((tournament) => {
     console.log(tournament.getID());
});
// 1122334455
FBInstant.tournament
    .joinAsync('1122334455')
    .then(function() {
         // Context switch completed successfully.
    });
  • Throws INVALID_OPERATION
  • Throws INVALID_PARAM
  • Throws SAME_CONTEXT
  • Throws NETWORK_FAILURE
  • Throws USER_INPUT
  • Throws TOURNAMENT_NOT_FOUND

Returns [Promise][1] A promise that resolves when the game has switched into the specified tournament context, or rejects otherwise.


getTournamentsAsync( )

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.


Examples
FBInstant.tournament.getTournamentsAsync()
.then(tournaments => {
     // tournament list
});
  • Throws NETWORK_FAILURE
  • Throws INVALID_OPERATION

Returns [Promise][1]<[Array][5]<[Tournament][4]>> A promise that resolves with an array of [Tournament][9] objects if the tournaments are fetched, or rejects otherwise.


player

Contains functions and properties related to the current player.


Properties

  • getID function (): [string][6]? Gets the player's unique identifier
  • getASIDAsync function (): [Promise][1]<[string][6]?> Gets the player's application-scoped ID
  • getSignedASIDAsync function (): [Promise][1]<[SignedASID][10]?> Gets the player's signed application-scoped ID
  • getSignedPlayerInfoAsync function ([string][6]?): [Promise][1]<[SignedPlayerInfo][11]> Gets the player's signed info
  • canSubscribeBotAsync function (): [Promise][1]<[boolean][2]> Checks if the player can subscribe to the game bot
  • isSubscribedBotAsync function (): [Promise][1]<[boolean][2]> Checks if the player is subscribed to the game bot
  • subscribeBotAsync function (): [Promise][1] Requests the player to subscribe to the game bot
  • getDataAsync function ([Array][5]<[string][6]>): [Promise][1]<[Object][12]> Gets player data from cloud storage
  • setDataAsync function ([Object][12]): [Promise][1] Sets player data to cloud storage
  • flushDataAsync function (): [Promise][1] Immediately persists player data to cloud storage
  • getConnectedPlayersAsync function (): [Promise][1]<[Array][5]<[ConnectedPlayer][13]>> Gets the player's connected players

getID( )

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.


Examples
// This function should be called after FBInstant.initializeAsync()
// resolves.
var playerID = FBInstant.player.getID();

Returns [string][6]? A unique identifier for the player.


getASIDAsync( )

NOTE: This function will only return ASIDs for users migrating over from your canvas app or for users that had previously accepted Terms of Service for you game. You should rely on player ID for all of your use cases.

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.


Examples
// This function should be called after FBInstant.initializeAsync()
// resolves.
var playerASID = FBInstant.player.getASIDAsync().then(
asid => console.log(asid);
);

Returns [Promise][1]<[string][6]?> A unique identifier for the player.


getSignedASIDAsync( )

NOTE: This function will only return ASIDs for users migrating over from your canvas app or for users that had previously accepted Terms of Service for you game. You should rely on player ID for all of your use * cases. 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.


Examples
// This function should be called after FBInstant.initializeAsync()
// resolves.
var playerASID = FBInstant.player.getSignedASIDAsync()
    .then(function (result) {
        result.getASID();
    });

Returns [Promise][1]<[SignedASID][10]?> A promise that resolves with a [SignedASID][14] object.


getSignedPlayerInfoAsync( )

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.


Parameters
  • requestPayload [string][6]? A developer-specified payload to include in the signed response.

Examples
// 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);
    });
  • Throws INVALID_PARAM
  • Throws NETWORK_FAILURE
  • Throws CLIENT_UNSUPPORTED_OPERATION

Returns [Promise][1]<[SignedPlayerInfo][11]> A promise that resolves with a [SignedPlayerInfo][15] object.


canSubscribeBotAsync( )

Returns a promise that resolves with whether the player can subscribe to the game bot or not.


Examples
// This function should be called before FBInstant.player.subscribeBotAsync()
FBInstant.player.canSubscribeBotAsync().then(
    can_subscribe => console.log(can_subscribe)
);
// 'true'
  • Throws RATE_LIMITED
  • Throws INVALID_OPERATION
  • Throws CLIENT_UNSUPPORTED_OPERATION

Returns [Promise][1]<[boolean][2]> 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.


isSubscribedBotAsync( )

Returns a promise that resolves with whether the player is already subscribed to the game bot or not.


Examples
FBInstant.player.isSubscribedBotAsync()
    .then(function (isSubscribed) {
        // Custom logic
    })
)

Returns [Promise][1]<[boolean][2]> Whether a player is already subscribed to the game bot or not. This is to perform custom logic for players who are subscribed to the game bot. To check whether to prompt the user to subscribe, canSubscribeBotAsync should be used instead.


subscribeBotAsync( )

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.


Examples
FBInstant.player.subscribeBotAsync().then(
    // Player is subscribed to the bot
).catch(function (e) {
    // Handle subscription failure
});
  • Throws INVALID_PARAM
  • Throws PENDING_REQUEST
  • Throws CLIENT_REQUIRES_UPDATE

Returns [Promise][1] A promise that resolves if player successfully subscribed to the game bot, or rejects if request failed or player chose to not subscribe.


getDataAsync( )

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


Parameters
  • keys [Array][5]<[string][6]> An array of unique keys to retrieve data for.

Examples
FBInstant.player
    .getDataAsync(['achievements', 'currentLife'])
    .then(function(data) {
         console.log('data is loaded');
         var achievements = data['achievements'];
         var currentLife = data['currentLife'];
    });
  • Throws INVALID_PARAM
  • Throws NETWORK_FAILURE
  • Throws CLIENT_UNSUPPORTED_OPERATION

Returns [Promise][1]<[Object][12]> 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.


setDataAsync( )

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.


Parameters
  • data [Object][12] 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.

Examples
FBInstant.player
    .setDataAsync({
        achievements: ['medal1', 'medal2', 'medal3'],
        currentLife: 300,
    })
    .then(function() {
        console.log('data is set');
    });
  • Throws INVALID_PARAM
  • Throws NETWORK_FAILURE
  • Throws PENDING_REQUEST
  • Throws CLIENT_UNSUPPORTED_OPERATION

Returns [Promise][1] 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.


flushDataAsync( )

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.


Examples
FBInstant.player
    .setDataAsync({
        achievements: ['medal1', 'medal2', 'medal3'],
        currentLife: 300,
    })
    .then(FBInstant.player.flushDataAsync)
    .then(function() {
        console.log('Data persisted to FB!');
    });
  • Throws INVALID_PARAM
  • Throws NETWORK_FAILURE
  • Throws PENDING_REQUEST
  • Throws CLIENT_UNSUPPORTED_OPERATION

Returns [Promise][1] A promise that resolves when changes have been persisted successfully, and rejects if the save fails.


getConnectedPlayersAsync( )

Fetches an array of ConnectedPlayer objects containing player IDs of active players (people who played the game in the last 90 days) that are connected to the current player.


Examples
var connectedPlayers = FBInstant.player.getConnectedPlayersAsync()
    .then(function(players) {
        console.log(players.map(function(player) {
            return {
                id: player.getID(),
            }
        }));
    });
// [{id: '123456789'}, {id: '987654321'}]
  • Throws NETWORK_FAILURE
  • Throws CLIENT_UNSUPPORTED_OPERATION

Returns [Promise][1]<[Array][5]<[ConnectedPlayer][13]>> A promise that resolves with a list of connected player objects. NOTE: This function should not be called until FBInstant.initializeAsync() has resolved.


context

Contains functions and properties related to the current game context.


Properties

  • getID function (): [string][6]? Gets the ID of the current context
  • switchAsync function ([string][6], [boolean][2]?): [Promise][1] Switches to a different context
  • createAsync function ([string][6]): [Promise][1] Creates a new context
  • getPlayersAsync function (): [Promise][1]<[Array][5]<[ContextPlayer][16]>> Gets players in the current context
  • chooseAsync function ([Object][12]?): [Promise][1] Opens a context selection dialog

getID( )

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.


Examples
// This function should be called after FBInstant.initializeAsync()
// resolves.
var contextID = FBInstant.context.getID();

Returns [string][6]? A unique identifier for the current game context.


switchAsync( )

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.


Parameters
  • id [string][6] ID of the desired context or the string SOLO to switch into a solo context.
  • switchSilentlyIfSolo [boolean][2] If switching into a solo context, set this to true to switch silently, with no confirmation dialog or toast. This only has an effect when switching into a solo context. (optional, default false)

Examples
console.log(FBInstant.context.getID());
// 1122334455
FBInstant.context
    .switchAsync('1234567890')
    .then(function() {
        console.log(FBInstant.context.getID());
        // 1234567890
    });
  • Throws INVALID_PARAM
  • Throws SAME_CONTEXT
  • Throws NETWORK_FAILURE
  • Throws USER_INPUT
  • Throws PENDING_REQUEST
  • Throws CLIENT_UNSUPPORTED_OPERATION

Returns [Promise][1] A promise that resolves when the game has switched into the specified context, or rejects otherwise.


createAsync( )

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.


Parameters
  • suggestedPlayerIDs ([string][6] | [Array][5]<[String][6]>)? A list of game suggested playerIDs or a single suggested playerID or no input

Examples
console.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
    });
  • Throws INVALID_PARAM
  • Throws SAME_CONTEXT
  • Throws NETWORK_FAILURE
  • Throws USER_INPUT
  • Throws PENDING_REQUEST
  • Throws CLIENT_UNSUPPORTED_OPERATION

Returns [Promise][1] A promise that resolves when the game has switched into the new context, or rejects otherwise.


getPlayersAsync( )

Gets an array of [ContextPlayer][17] 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.


Examples
var contextPlayers = FBInstant.context.getPlayersAsync()
    .then(function(players) {
        console.log(players.map(function(player) {
            return {
                id: player.getID(),
            }
        }));
    });
// [{id: '123456789'}, {id: '987654321'}]
  • Throws NETWORK_FAILURE
  • Throws CLIENT_UNSUPPORTED_OPERATION
  • Throws INVALID_OPERATION

Returns [Promise][1]<[Array][5]<[ContextPlayer][16]>> A promise that resolves with a list of [ContextPlayer][17] objects. NOTE: This function should not be called until FBInstant.initializeAsync() has resolved.


chooseAsync( )

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.


Parameters
  • options [Object][12]? An object specifying conditions on the contexts that should be offered.
  • options.filters [Array][5]<[ContextFilter][18]>? The set of filters to apply to the context suggestions.
  • options.maxSize [number][7]? The maximum number of participants that a suggested context should ideally have.
  • options.minSize [number][7]? The minimum number of participants that a suggested context should ideally have.

Examples
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
    });
  • Throws INVALID_PARAM
  • Throws SAME_CONTEXT
  • Throws NETWORK_FAILURE
  • Throws USER_INPUT
  • Throws PENDING_REQUEST
  • Throws CLIENT_UNSUPPORTED_OPERATION

Returns [Promise][1] 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).


room

Contains functions and properties related to the messenger rooms environment.


Properties

  • getCurrentMatchAsync function (): [Promise][1]<[LiveMatch][19]> Retrieves the current real-time match for the gameplay environment

getCurrentMatchAsync( )

Retrieves the current real-time match for the gameplay environment, if one exists.


Examples
FBInstant.room.getCurrentMatchAsync()
    .then(function(match) {
        ...
    });
  • Throws [APIError][20] With code INVALID_OPERATION if the operation cannot be performed
  • Throws [APIError][20] With code INVALID_PARAM if any parameters are invalid
  • Throws [APIError][20] With code LIVE_MATCH_NOT_FOUND if no live match exists for the current context

Returns [Promise][1]<[LiveMatch][19]> A promise that resolves with the current live match being played in this session


globalLeaderboard

Contains functions and properties related to Global Leaderboards.


Properties

  • getScoreAsync function ([string][6]): [Promise][1]<[number][7]?> Retrieves the player's score in the leaderboard
  • setScoreAsync function ([string][6], [number][7]): [Promise][1] Updates the player's score in a leaderboard
  • getTopEntriesAsync function ([string][6], [number][7]?): [Promise][1]<[Array][5]<[GlobalLeaderboardEntry][21]>> Retrieves the top scoring entries in the leaderboard
  • getTopFriendEntriesAsync function ([string][6], [number][7]?): [Promise][1]<[Array][5]<[GlobalLeaderboardEntry][21]>> Retrieves the entries of the friends of the player in the leaderboard

getScoreAsync( )

Retrieves the player's score in the leaderboard. If the player has no score, this will return null.


Parameters
  • leaderboardID [string][6] The ID of the leaderboard where this score will be added.

Examples
FBInstant.globalLeaderboard.getScoreAsync('1122334455')
    .then(function(score) {
        if (score !== null) {
            console.log('Your score: ' + score);
        } else {
            console.log('You have not set a score yet');
        }
    });
  • Throws [APIError][20] If the leaderboardID is invalid or the request fails

Returns [Promise][1]<[number][7]?> Resolves with the player's score, or null if the player has no score


setScoreAsync( )

Updates the player's score in a leaderboard. If the player has an existing score, the old score will only be replaced if the new score is better.


Parameters
  • leaderboardID [string][6] The ID of the leaderboard where this score will be added
  • score [number][7] The new score for the player. Must be a 64-bit integer number

Examples
FBInstant.globalLeaderboard.setScoreAsync('1122334455', 100)
    .then(function() {
        console.log('Score successfully updated');
    })
    .catch(function(error) {
        console.error('Error updating score: ' + error.message);
    });
  • Throws [APIError][20] If the leaderboardID is invalid, the score is invalid, or the request fails

Returns [Promise][1] Resolves when the score has been successfully updated


getTopEntriesAsync( )

Retrieves the top scoring entries in the leaderboard, ordered by score ranking in the leaderboard.


Parameters
  • leaderboardID [string][6] The ID of the leaderboard to fetch
  • limit [number][7]? The maximum number of scores to fetch

Examples
FBInstant.globalLeaderboard.getTopEntriesAsync('1122334455', 5)
.then(function(entries) {
     entries.forEach(function(entry) {
         console.log(entry.getScore());
         console.log(entry.getPlayer().getSessionID());
     });
});
  • Throws [APIError][20] If the leaderboardID is invalid, a request is already pending, or the request fails

Returns [Promise][1]<[Array][5]<[GlobalLeaderboardEntry][21]>> Resolves to an array of GlobalLeaderboardEntry objects


getTopFriendEntriesAsync( )

Retrieves the entries of the friends of the player in the leaderboard, ordered by score ranking in the leaderboard.


Parameters
  • leaderboardID [string][6] The ID of the leaderboard to fetch
  • limit [number][7]? The maximum number of scores to fetch

Examples
FBInstant.globalLeaderboard.getTopFriendEntriesAsync('1122334455', 5)
.then(function(entries) {
     entries.forEach(function(entry) {
         console.log(entry.getScore());
         console.log(entry.getPlayer().getSessionID());
     });
});
  • Throws [APIError][20] If the leaderboardID is invalid, a request is already pending, or the request fails

Returns [Promise][1]<[Array][5]<[GlobalLeaderboardEntry][21]>> Resolves to an array of GlobalLeaderboardEntry objects


payments

Contains functions and properties related to payments and purchases of game products.


Properties

  • getCatalogAsync function (): [Promise][1]<[Array][5]<[Product][22]>> Fetches the game's product catalog
  • purchaseAsync function ([PurchaseConfig][23]): [Promise][1]<[Purchase][24]> Begins the purchase flow for a specific product
  • getPurchasesAsync function (): [Promise][1]<[Array][5]<[Purchase][24]>> Fetches all of the player's unconsumed purchases
  • consumePurchaseAsync function ([string][6]): [Promise][1] Consumes a specific purchase belonging to the current player
  • onReady function ([Function][25]): void Sets a callback to be triggered when Payments operations are available

getCatalogAsync( )

Fetches the game's product catalog.


Examples
FBInstant.payments.getCatalogAsync().then(function (catalog) {
    console.log(catalog); // [{productID: '12345', ...}, ...]
});
  • Throws CLIENT_UNSUPPORTED_OPERATION
  • Throws PAYMENTS_NOT_INITIALIZED
  • Throws NETWORK_FAILURE

Returns [Promise][1]<[Array][5]<[Product][22]>> The set of products that are registered to the game.


purchaseAsync( )

Begins the purchase flow for a specific product. Will immediately reject if called before FBInstant.startGameAsync() has resolved.


Parameters
  • purchaseConfig [PurchaseConfig][23] The purchase's configuration details.

Examples
FBInstant.payments.purchaseAsync({
    productID: '12345',
    developerPayload: 'foobar',
}).then(function (purchase) {
    console.log(purchase);
    // {productID: '12345', purchaseToken: '54321', developerPayload: 'foobar', ...}
});
  • Throws CLIENT_UNSUPPORTED_OPERATION
  • Throws PAYMENTS_NOT_INITIALIZED
  • Throws INVALID_PARAM
  • Throws NETWORK_FAILURE
  • Throws INVALID_OPERATION
  • Throws USER_INPUT

Returns [Promise][1]<[Purchase][24]> A Promise that resolves when the product is successfully purchased by the player. Otherwise, it rejects.


getPurchasesAsync( )

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.


Examples
FBInstant.payments.getPurchasesAsync().then(function (purchases) {
    console.log(purchase);
    // [{productID: '12345', ...}, ...]
});
  • Throws CLIENT_UNSUPPORTED_OPERATION
  • Throws PAYMENTS_NOT_INITIALIZED
  • Throws NETWORK_FAILURE

Returns [Promise][1]<[Array][5]<[Purchase][24]>> The set of purchases that the player has made for the game.


consumePurchaseAsync( )

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.


Parameters
  • purchaseToken [string][6] The purchase token of the purchase that should be consumed.

Examples
FBInstant.payments.consumePurchaseAsync('54321').then(function () {
    // Purchase successfully consumed!
    // Game should now provision the product to the player
});
  • Throws CLIENT_UNSUPPORTED_OPERATION
  • Throws PAYMENTS_NOT_INITIALIZED
  • Throws INVALID_PARAM
  • Throws NETWORK_FAILURE

Returns [Promise][1] A Promise that resolves when the purchase has been consumed successfully.


onReady( )

Sets a callback to be triggered when Payments operations are available.


Parameters
  • callback [Function][25] The callback function to be executed when Payments are available.

Examples
FBInstant.payments.onReady(function () {
    console.log('Payments Ready!')
});

Returns void


overlayViews

Contains functions for the creation and management of Meta controlled overlay views rendering user profile information


Properties

  • createOverlayView function ([string][6], [string][6]?, [Object][12]?, [function][25]?, [function][25]?): [OverlayView][26] Creates an overlay view from an XML file
  • createOverlayViewAsync function ([string][6], [HTMLElement][27], [string][6]?, [string][6]?, [Object][12]?): [Promise][1]<[OverlayView][26]> Creates an overlay view from an XML file and returns a promise
  • createOverlayViewWithXMLString function ([string][6], [string][6]?, [Object][12]?, [function][25]?, [function][25]?, [string][6]?): [OverlayView][26] Creates an overlay view from an XML string
  • createOverlayViewWithXMLStringAsync function ([string][6], [HTMLElement][27], [string][6]?, [string][6]?, [Object][12]?, [string][6]?): [Promise][1]<[OverlayView][26]> Creates an overlay view from an XML string and returns a promise
  • createProfilePictureOverlayViewAsync function ([HTMLElement][27], [string][6]?, [string][6]?): [Promise][1]<[OverlayView][26]> Creates a profile picture overlay view
  • createProfileNameOverlayViewAsync function ([HTMLElement][27], [string][6]?, [string][6]?, [string][6]?): [Promise][1]<[OverlayView][26]> Creates a profile name overlay view
  • setCustomEventHandler function (function ([string][6], [string][6]): void): void Sets a custom event handler for overlay view events
  • getOverlayViews function (): [Map][28]<[string][6], [OverlayView][26]> Returns a map of all created overlay views

createOverlayViewAsync( )

Similar to FBInstant.overlayViews.createOverlayView() but returns a promise instead. Creates an Instant Games overlay view that can be used to render user's information as defined by the layout specified in the provided view's xml file.


Parameters
  • fullyQualifiedOverlayViewFilename [string][6] The fully qualified name of the overlay view XML file (relative to the root of your game bundle) to be used as the layout. For example, "overlay_views/profile_overlay.xml" given profile_overlay.xml is present in an 'overlay_views' folder in the root of your game bundle
  • domElement [HTMLElement][27] The HTMLElement to attach the iframe element to via the appendChild method. If you pass in document.body, we will perform document.body.appendChild(overlayView.iframeElement) for you
  • iFrameStyle [string][6]? The css inline style to apply to the iframe element
  • pathToCSS [string][6]? The String of the path that holds the file the Overlay View will use for styling. For example, "css/styles.css"
  • initialData [Object][12]? The initial data to be passed to the view

Examples
const overlayView = await FBInstant.overlayViews.createOverlayViewAsync(
"overlay_views/profile_overlay.xml",
document.body,
"width: 100px; height: 100px;",
"css/styles.css",
{score: 30}
);

Returns [Promise][1]<[OverlayView][26]> A promise that resolves with the overlay view object if successful, otherwise rejects with an [APIError][29]. Note that you would still have to call showAsync() on the overlay view in order to display it


createOverlayViewWithXMLStringAsync( )

Similar to createOverlayViewWithXMLString but returns a promise instead. Creates an Instant Games overlay view that can be used to render user's information as defined by the layout specified in the string passed to this function


Parameters
  • overlayViewContentOverride [string][6] The String of the Overlay XML that is passed into Instant Game SDK
  • domElement [HTMLElement][27] The HTMLElement to attach the iframe element to via the appendChild method. If you pass in document.body, we will perform document.body.appendChild(overlayView.iframeElement) for you
  • iFrameStyle [string][6]? The css inline style to apply to the iframe element
  • pathToCSS [string][6]? The String of the path that holds the file the Overlay View will use for styling. For example, "css/styles.css"
  • initialData [Object][12]? The initial data to be passed to the view
  • pathToOverlayFiles [string][6]? The String of the path that holds the overlay related files. For example, "ig_views"

Examples
const overlayView = await FBInstant.overlayViews.createOverlayViewWithXMLStringAsync(
"<View></View>",
document.body,
"width: 100px; height: 100px;",
"css/styles.css",
{score: 30},
"overlay_views",
);

Returns [Promise][1]<[OverlayView][26]> A promise that resolves with the overlay view object if successful, otherwise rejects with an [APIError][29]


createOverlayView( )

Creates an Instant Games overlay view that can be used to render user's information as defined by the layout specified in the provided view's xml file


Parameters
  • fullyQualifiedOverlayViewFilename [string][6] The fully qualified name of the overlay view XML file (relative to the root of your game bundle) to be used as the layout. For example, "overlay_views/profile_overlay.xml" given profile_overlay.xml is present in an 'overlay_views' folder in the root of your game bundle
  • pathToCSS [string][6]? The String of the path that holds the file the Overlay View will use for styling. For example, "css/styles.css"
  • initialData [Object][12]? The initial data to be passed to the view
  • onInitializedSuccessCallback function ([OverlayView][26]): void? The callback to be called when the view is successfully initialized and ready to be shown
  • onInitializedErrorCallback function ([OverlayView][26], [APIError][20]): void? The callback to be called when an error occurs while initializing the view

Examples
FBInstant.overlayViews.createOverlayView(
"overlay_views/profile_overlay.xml",
"css/styles.css",
{score: 30},
(overlayView) => console.log("overlay view created successfully"),
(overlayView, error) => console.log("overlay view creation failed with error: ", error)
);

Returns [OverlayView][26] The created overlay view instance


createOverlayViewWithXMLString( )

Creates an Instant Games overlay view that can be used to render user's information as defined by the layout specified in the string passed to this function


Parameters
  • overlayViewContentOverride [string][6] The String of the Overlay XML that is passed into Instant Game SDK
  • pathToCSS [string][6]? The String of the path that holds the file the Overlay View will use for styling. For example, "css/styles.css"
  • initialData [Object][12]? The initial data to be passed to the view
  • onInitializedSuccessCallback function ([OverlayView][26]): void? The callback to be called when the view is successfully initialized and ready to be shown
  • onInitializedErrorCallback function ([OverlayView][26], [APIError][20]): void? The callback to be called when an error occurs while initializing the view
  • pathToOverlayFiles [string][6]? The String of the path that holds the overlay related files. For example, "ig_views"

Examples
FBInstant.overlayViews.createOverlayViewWithXMLString("<View></View>", "css/styles.css", {score: 30}, (overlayView) => console.log("overlay view created successfully"), (overlayView, error) => console.log("overlay view creation failed with error: ", error), "overlay_views");

Returns [OverlayView][26] The created overlay view instance


createProfilePictureOverlayViewAsync( )

Creates a profile picture overlay view that can be used to render the user's profile picture without requiring having to specify XML.


Parameters
  • domElement [HTMLElement][27] The HTMLElement to attach the iframe element to via the appendChild method. If you pass in document.body, we will perform document.body.appendChild(overlayView.iframeElement) for you
  • imageStyle [string][6]? The css inline style to apply to the profile picture
  • iFrameStyle [string][6]? The css inline style to apply to the iframe element

Examples
const overlayView = await FBInstant.overlayViews.createProfilePictureOverlayViewAsync(document.body, "width: 100px; height: 100px;", "width: 100px; height: 100px;");

Returns [Promise][1]<[OverlayView][26]> A promise that resolves with the overlay view object if successful, otherwise rejects with an [APIError][29]. Note that you would still have to call showAsync() on the overlay view in order to display it.


createProfileNameOverlayViewAsync( )

Creates a user profile name overlay view that can be used to render the user's first name without requiring having to specify XML.


Parameters
  • domElement [HTMLElement][27] The HTMLElement to attach the iframe element to via the appendChild method. If you pass in document.body, we will perform document.body.appendChild(overlayView.iframeElement) for you
  • textStyle [string][6]? The css inline style to apply to the profile name text
  • iFrameStyle [string][6]? The css inline style to apply to the iframe element
  • pathToCss [string][6]? Optional path to CSS file for additional styling

Examples
const overlayView = await FBInstant.overlayViews.createProfileNameOverlayViewAsync(document.body, "width: 100px; height: 100px;", "width: 100px; height: 100px;");

Returns [Promise][1]<[OverlayView][26]> A promise that resolves with the overlay view object if successful, otherwise rejects with an [APIError][29]. Note that you would still have to call showAsync() on the overlay view in order to display it.


setCustomEventHandler( )

Set a custom event handler for a callback string that is triggered from any of your overlay views.


Parameters
  • handler function ([string][6], [string][6]): void The callback to be called when this custom event is triggered. The callback receives two parameters:- eventStr: A string containing the event data
  • overlayID: A string identifying which overlay triggered the event

Examples
FBInstant.overlayViews.setCustomEventHandler((eventStr, overlayID) => {
     document.getElementById('overlayCustomEventOutput').innerHTML +=
             ' |' + eventStr + ' triggered by ' + overlayID + '| ';
});

Returns void


getOverlayViews( )

Returns a map of all the overlay views that have been created.

Returns [Map][28]<[string][6], [OverlayView][26]> Returns a map of all the overlay views that have been created


inviteAsync( )

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 invite 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 of whether the user actually invited people or not. The sections included in the dialog can be customized by using the sections parameter. This can specify which sections to include, how many results to include in each section, and what order the sections should appear in. The last section will include as many results as possible. If no sections are specified, the default section settings will be applied. The filters parameter allows for filtering the results. If no results are returned when the filters are applied, the results will be generated without the filters.


Parameters

  • payload [InviteWithOverlayPayload][30] Specify what to share. See example for details.

Examples

FBInstant.inviteAsync({
    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!'
        }
    },
    data: { myReplayData: '...' }
}).then(function() {
    // continue with the game.
});
FBInstant.inviteAsync({
    image: base64Picture,
    text: {
        default: 'X just invaded Y\'s village!',
        localizations: {
            ar_AR: 'X \u0641\u0642\u0637 \u063A\u0632\u062A ' +
                '\u0642\u0631\u064A\u0629!',
            en_US: 'X just invaded Y\'s village!',
            es_LA: '\u00A1X acaba de invadir el pueblo de Y!'
        }
    },
    notificationText: {
        default: 'X just performed B action, play now!',
        localizations: {
            ar_AR: 'X \u0641\u0642\u0637 \u063A\u0632\u062A'
        }
    },
    cta: {
        default: 'Join the fight!',
        localizations: {
            ar_AR: '\u0627\u0646\u0636\u0645 \u0625\u0644\u0649' +
                '\u0627\u0644\u0642\u062A\u0627\u0644!',
            en_US: 'Join the fight!',
            es_LA: '\u00A1\u00DAnete a la pelea!'
        }
    },
    dialogTitle: {
        default: 'Enlist your friends',
        localizations: {
            ar_AR: '\u062D\u0634\u062F \u0623\u0635\u062F\u0642' +
                '\u0627\u0621\u0643',
            en_US: 'Enlist your friends',
            es_LA: 'Alistar a tus amigos'
        }
    },
    filters: ['NEW_CONTEXT_ONLY', 'EXISTING_PLAYERS_ONLY'],
    sections: [
        {sectionType: 'GROUPS', maxResults: 2},
        {sectionType: 'USERS'}
    ],
    data: { myReplayData: '...' }
}).then(function() {
    // continue with the game.
});
  • Throws INVALID_PARAM
  • Throws NETWORK_FAILURE
  • Throws PENDING_REQUEST
  • Throws CLIENT_UNSUPPORTED_OPERATION
  • Throws INVALID_OPERATION

Returns [Promise][1] A promise that resolves when the share is completed or cancelled.


getLocale( )

The current locale. See [https://lookaside.facebook.com/developers/resources/?id=FacebookLocales.xml][31] 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.


Examples

// This function should be called after FBInstant.initializeAsync()
// resolves.
var locale = FBInstant.getLocale(); // 'en_US'

Returns [string][6] The current locale.


getPlatform( )

The platform on which the game is currently running. The value will always be null until FBInstant.initializeAsync() resolves.


Examples

// This function should be called after FBInstant.initializeAsync()
// resolves.
var platform = FBInstant.getPlatform(); // 'IOS'

Returns [Platform][32]? The platform on which the game is running.


getSDKVersion( )

The string representation of this SDK version.


Examples

// This function should be called after FBInstant.initializeAsync()
// resolves.
var sdkVersion = FBInstant.getSDKVersion(); // '2.0'

Returns [string][6] The SDK version.


initializeAsync( )

Initializes the SDK library. This should be called before any other SDK functions.


Examples

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();
});
  • Throws INVALID_OPERATION

Returns [Promise][1] A promise that resolves when the SDK is ready to use.


shareAsync( )

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.


Parameters

  • payload [ShareWithOverlayPayload][33] Specify what to share. See example for details.

Examples

FBInstant.shareAsync({
    intent: 'REQUEST',
    image: base64Picture,
    text: 'X is asking for your help!',
    data: { myReplayData: '...' },
    shareDestination: ['NEWSFEED', 'GROUP', 'COPY_LINK', 'MESSENGER']
    switchContext: false,
}).then(function() {
    // continue with the game.
});
  • Throws INVALID_PARAM
  • Throws NETWORK_FAILURE
  • Throws PENDING_REQUEST
  • Throws CLIENT_UNSUPPORTED_OPERATION
  • Throws INVALID_OPERATION

Returns [Promise][1] A promise that resolves when the share is completed or cancelled.


postSessionScore( )

Posts a player's score to Facebook. 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.


Parameters

  • score [number][7] An integer value representing the player's score at the end of an activity.

Examples

function onScore(score) {
    if (score > bestSessionScore) {
        bestSessionScore = score;
        FBInstant.postSessionScore(bestSessionScore);
    }
}

Returns void


postSessionScoreAsync( )

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.


Parameters

  • score [number][7] An integer value representing the player's score at the end of an activity.

Examples

function onScore(score) {
    if (score > bestSessionScore) {
        bestSessionScore = score;
        FBInstant.postSessionScoreAsync(bestSessionScore)
            .then(() => {
                ...
            });
    }
}

Returns [Promise][1] 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.


getTournamentAsync( )

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.


Examples

FBInstant.getTournamentAsync()
    .then(function(tournament) {
         console.log(tournament.getContextID());
         console.log(tournament.getEndTime());
    });
  • Throws PENDING_REQUEST
  • Throws NETWORK_FAILURE
  • Throws INVALID_OPERATION
  • Throws TOURNAMENT_NOT_FOUND

Returns [Promise][1]<[Tournament][4]> A promise that resolves with the matched instant tournament a user is playing. This rejects if no instant tournament is found.


performHapticFeedbackAsync( )

Requests and performs haptic feedback on supported devices.


Examples

FBInstant.performHapticFeedbackAsync();
  • Throws CLIENT_UNSUPPORTED_OPERATION
  • Throws INVALID_OPERATION

Returns [Promise][1] haptic feedback requested successfully


updateAsync( )

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.


Parameters

  • payload [CustomUpdateWithOverlayPayload][34] A payload that describes the update.

Examples

// 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!',
        }
    }
    notificationText: {
        default: 'X just performed B action, play now!',
        localizations: {
            ar_AR: 'X \u0641\u0642\u0637 \u063A\u0632\u062A'
        }
    }
    template: 'VILLAGE_INVASION',
    data: { myReplayData: '...' },
    strategy: 'IMMEDIATE',
    notification: 'NO_PUSH',
}).then(function() {
    // closes the game after the update is posted.
    FBInstant.quit();
});
  • Throws INVALID_PARAM
  • Throws PENDING_REQUEST
  • Throws INVALID_OPERATION

Returns [Promise][1] A promise that resolves when Facebook gives control back to the game.


switchGameAsync( )

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.


Parameters

  • appID [string][6] 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][35].
  • data [Object][12]? 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.

Examples

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
});
  • Throws USER_INPUT
  • Throws INVALID_PARAM
  • Throws PENDING_REQUEST
  • Throws CLIENT_REQUIRES_UPDATE

Returns [Promise][1] A promise that resolves when the game switch is successful.


canCreateShortcutAsync( )

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.


Examples

FBInstant.canCreateShortcutAsync()
    .then(function(canCreateShortcut) {
        if (canCreateShortcut) {
            FBInstant.createShortcutAsync()
                .then(function() {
                    // Shortcut created
                })
                .catch(function() {
                    // Shortcut not created
                });
        }
    });
  • Throws PENDING_REQUEST
  • Throws CLIENT_REQUIRES_UPDATE
  • Throws INVALID_OPERATION

Returns [Promise][1]<[boolean][2]> Promise that resolves with true if the game can request the player create a shortcut to the game, and false otherwise


createShortcutAsync( )

Prompts the user to create a shortcut to the game if they are eligible to Can only be called once per session. (see [canCreateShortcutAsync][36])


Examples

FBInstant.canCreateShortcutAsync()
    .then(function(canCreateShortcut) {
        if (canCreateShortcut) {
            FBInstant.createShortcutAsync()
                .then(function() {
                    // Shortcut created
                })
                .catch(function() {
                    // Shortcut not created
                });
        }
    });
  • Throws USER_INPUT
  • Throws PENDING_REQUEST
  • Throws CLIENT_REQUIRES_UPDATE
  • Throws INVALID_OPERATION

Returns [Promise][1] A promise that resolves when the shortcut is created, or rejects if creation fails.


setLoadingProgress( )

Report the game's initial loading progress.


Parameters

  • percentage [number][7] A number between 0 and 100.

Examples

FBInstant.setLoadingProgress(50); // Assets are 50% loaded

Returns void


getSupportedAPIs( )

Provides a list of API functions that are supported by the client.


Examples

// This function should be called after FBInstant.initializeAsync()
// resolves.
FBInstant.getSupportedAPIs();
// ['getLocale', 'initializeAsync', 'player.getID', 'context.getType', ...]

Returns [Array][5]<[string][6]> List of API functions that the client explicitly supports.


getEntryPointData( )

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.


Examples

// This function should be called after FBInstant.initializeAsync()
// resolves.
const entryPointData = FBInstant.getEntryPointData();

Returns [Object][12]? Data associated with the current entry point.


getEntryPointAsync( )

Returns the entry point that the game was launched from.

This function should not be called until FBInstant.startGameAsync has resolved.


Examples

// This function should be called after FBInstant.initializeAsync()
// resolves.
FBInstant.getEntryPointAsync().then(entrypoint => console.log(entrypoint));
// 'admin_message'

Returns [Promise][1]<[string][6]> The name of the entry point from which the user started the game


setSessionData( )

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.


Parameters

  • sessionData [Object][12] An arbitrary data object, which must be less than or equal to 1000 characters when stringified.

Examples

FBInstant.setSessionData({coinsEarned: 10, eventsSeen: ['start', ...]});

Returns void


startGameAsync( )

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.


Examples

FBInstant.startGameAsync().then(function() {
    myGame.start();
});
  • Throws INVALID_PARAM
  • Throws CLIENT_UNSUPPORTED_OPERATION

Returns [Promise][1] A promise that resolves when the game should start.


quit( )

Quits the game.


Examples

FBInstant.quit();

Returns void


logEvent( )

Log an app event with FB Analytics. See [https://developers.facebook.com/docs/javascript/reference/v2.8#app_events][37] for more details about FB Analytics.


Parameters

  • eventName [string][6] Name of the event. Must be 2 to 40 characters, and can only contain '_', '-', ' ', and alphanumeric characters.
  • valueToSum [number][7] An optional numeric value that FB Analytics can calculate a sum with.
  • parameters [Object][12] 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.

Examples

var logged = FBInstant.logEvent(
    'my_custom_event',
    42,
    {custom_property: 'custom_value'}
);

Returns [APIError][20]? The error if the event failed to log; otherwise returns null.


onPause( )

Set a callback to be fired when a pause event is triggered (when the user switches away from the window/tab on desktop or when the user switches apps on mobile).


Parameters

  • func [Function][25] A function to call when a pause event occurs.

Examples

FBInstant.onPause(function() {
    console.log('Pause event was triggered!');
    pauseGameplay();
})

Returns void


loadBannerAdAsync( )

Attempt to load or re-load a banner ad.


Parameters

  • placementID [string][6] The placement ID that's been set up in your Audience Network settings.
  • bannerPosition InstantGamesBannerAdPositionType? The position of the banner can be "top" or "bottom" of the screen. Defaults to "bottom".

Examples

FBInstant.loadBannerAdAsync(
    'my_placement_id', 'bottom'
).then(() => {
    console.log('success');
});
  • Throws RATE_LIMITED
  • Throws CLIENT_UNSUPPORTED_OPERATION

Returns [Promise][1] A promise that resolves after loading a banner ad, or rejects with a [APIError][29] if it couldn't be created.


hideBannerAdAsync( )

Attemp to hide a banner ad.


Examples

FBInstant.hideBannerAdAsync();
  • Throws CLIENT_UNSUPPORTED_OPERATION

Returns [Promise][1] A promise that resolves after the ad is hidden.


getInterstitialAdAsync( )

Attempt to create an instance of interstitial ad. This instance can then be preloaded and presented.


Parameters

  • placementID [string][6] The placement ID that's been setup in your Audience Network settings.

Examples

FBInstant.getInterstitialAdAsync(
    'my_placement_id'
).then(function(interstitial) {
    interstitial.getPlacementID(); // 'my_placement_id'
});
  • Throws ADS_TOO_MANY_INSTANCES
  • Throws CLIENT_UNSUPPORTED_OPERATION

Returns [Promise][1]<[AdInstance][38]> A promise that resolves with a [AdInstance][39], or rejects with a [APIError][29] if it couldn't be created.


getRewardedVideoAsync( )

Attempt to create an instance of rewarded video. This instance can then be preloaded and presented.


Parameters

  • placementID [string][6] The placement ID that's been setup in your Audience Network settings.

Examples

FBInstant.getRewardedVideoAsync(
    'my_placement_id'
).then(function(rewardedVideo) {
    rewardedVideo.getPlacementID(); // 'my_placement_id'
});
  • Throws ADS_TOO_MANY_INSTANCES
  • Throws CLIENT_UNSUPPORTED_OPERATION

Returns [Promise][1]<[AdInstance][38]> A promise that resolves with a [AdInstance][39], or rejects with a [APIError][29] if it couldn't be created.


getRewardedInterstitialAsync( )

Attempt to create an instance of rewarded interstitial. This instance can then be preloaded and presented.


Parameters

  • placementID [string][6] The placement ID that's been setup in your Audience Network settings.

Examples

FBInstant.getRewardedInterstitialAsync(
    'my_placement_id'
).then(function(rewardedInterstitial) {
    rewardedInterstitial.getPlacementID(); // 'my_placement_id'
});
  • Throws ADS_TOO_MANY_INSTANCES
  • Throws CLIENT_UNSUPPORTED_OPERATION

Returns [Promise][1]<[AdInstance][38]> A promise that resolves with a [AdInstance][39], or rejects with a [APIError][29] if it couldn't be created.


onContextChange( )

Set a callback to be fired when the game context changes. This can happen when a user joins or leaves a session, or when the player switches to a different context.


Parameters

  • onSuccess EventHandler A function to call when the context changes successfully. The function will receive the new context ID as a parameter.
  • onError EventHandler A function to call when an error occurs during context change. The function will receive an error object as a parameter.

Examples

FBInstant.onContextChange(
    function(contextID) {
        console.log('Context changed to: ' + contextID);
        updateGameUI();
    },
    function(error) {
        console.error('Context change error: ' + error);
    }
);

Returns void


PlayerData

Data structure containing player information for a context player.

Type: [Object][12]


Properties

  • id [string][6] The unique identifier of the player.

AdType

Constants representing the different types of ads available in the FBInstant SDK.

Type: [string][6]


INTERSTITIAL

Represents an interstitial ad that appears between game sessions or levels.

Type: [string][6]


REWARDED_VIDEO

Represents a rewarded video ad that offers in-game rewards for watching.

Type: [string][6]


REWARDED_INTERSTITIAL

Represents a rewarded interstitial ad that combines features of both ad types.

Type: [string][6]


GlobalLeaderboardPlayer

Represents a player in a global leaderboard.


Parameters

  • sessionScopeID [string][6] The session-scoped ID of the player

getSessionID( )

Returns the session-scoped ID of the player.

Returns [string][6] The session-scoped ID of the player


ConnectedPlayer

Represents information about a player who is connected to the current player for the restricted SDK (aka NEZP).


Parameters

  • playerID [string][6] The ID of the connected player.

getID( )

Get the id of the connected player for the restricted SDK (aka NEZP).

Returns [string][6] The ID of the connected player


SignedPlayerInfoData

Data structure containing player information and signature.

Type: [Object][12]


Properties

  • playerID [string][6] The unique identifier of the player.
  • signature [string][6] The signature to verify the player information.

SignedPlayerInfo

Represents information about the player along with a signature to verify that it indeed comes from Facebook.


Parameters

  • data [SignedPlayerInfoData][40] The player information and signature data.

getPlayerID( )

Get the id of the player.


Examples

FBInstant.player.getSignedPlayerInfoAsync()
    .then(function (result) {
        result.getPlayerID(); // same value as FBInstant.player.getID()
    });

Returns [string][6] The ID of the player


getSignature( )

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 5 steps:

  1. Split the signature into two parts delimited by the '.' character.
  2. Decode the first part (the encoded signature) with base64url encoding.
  3. Decode the second part (the response payload) with base64url encoding, which should be a string representation of a JSON object that has the following fields:
    • algorithm - always equals to HMAC-SHA256
    • issued_at - a unix timestamp of when this response was issued.
    • player_id - unique identifier of the player.
    • request_payload - the requestPayload string you specified when calling FBInstant.player.getSignedPlayerInfoAsync.
  4. Hash the whole response payload string using HMAC SHA-256 and your app secret and confirm that it is equal to the encoded signature.
  5. You may also wish to validate the issued_at timestamp in the response payload to ensure the request was made recently.

Signature validation should only happen on your server. Never do it on the client side as it will compromise your app secret key.


Examples

FBInstant.player.getSignedPlayerInfoAsync()
    .then(function (result) {
        result.getSignature();
        // Eii6e636mz5J47sfqAYEK40jYAwoFqi3x5bxHkPG4Q4.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImlzc3VlZF9hdCI6MTUwMDM5ODY3NSwicGxheWVyX2lkIjoiMTI0OTUyNTMwMTc1MjIwMSIsInJlcXVlc3RfcGF5bG9hZCI6Im15X2ZpcnN0X3JlcXVlc3QifQ
    });

Returns [string][6] The signature string.


SignedASIDData

Data structure containing app-scoped user ID and signature.

Type: [Object][12]


Properties

  • asid [string][6] The app-scoped user ID of the player.
  • signed_request [string][6] The signature to verify the ASID information.

SignedASID

Represents app-scoped user id of current player along with a signature to verify that it indeed comes from Facebook.


Parameters

  • data [SignedASIDData][41] The ASID information and signature data.

getASID( )

Get the app-scoped user id of the player.


Examples

FBInstant.player.getSignedASIDAsync()
    .then(function (result) {
        result.getASID();
    });

Returns [string][6] The ID of the player


getSignature( )

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 5 steps:

  1. Split the signature into two parts delimited by the '.' character.
  2. Decode the first part (the encoded signature) with base64url encoding.
  3. Decode the second part (the response payload) with base64url encoding, which should be a string representation of a JSON object that has the following fields:
    • algorithm - always equals to HMAC-SHA256
    • issued_at - a unix timestamp of when this response was issued.
    • asid - the app-scoped user id of the player.
  4. Hash the whole response payload string using HMAC SHA-256 and your app secret and confirm that it is equal to the encoded signature.
  5. You may also wish to validate the issued_at timestamp in the response payload to ensure the request was made recently.

Signature validation should only happen on your server. Never do it on the client side as it will compromise your app secret key.


Examples

FBInstant.player.getSignedASIDAsync()
    .then(function (result) {
        result.getSignature();
        // Eii6e636mz5J47sfqAYEK40jYAwoFqi3x5bxHkPG4Q4.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImlzc3VlZF9hdCI6MTUwMDM5ODY3NSwicGxheWVyX2lkIjoiMTI0OTUyNTMwMTc1MjIwMSIsInJlcXVlc3RfcGF5bG9hZCI6Im15X2ZpcnN0X3JlcXVlc3QifQ
    });

Returns [string][6] The signature string.


PurchasePlatform

Purchase Platforms that may be returned by subscriptions API, representing the platform by which the user made the purchase

Type: [string][6]


Properties

  • FB [string][6] The user made the purchase on web
  • GOOGLE [string][6] The user made the purchase in the Android apps
  • APPLE [string][6] Not eligible
  • OC [string][6] -- Not eligible
  • UNKNOWN [string][6]

Examples

FBInstant.payments.getPurchasesAsync()
    .then(function(purchases) {
        purchases.forEach((purchase) => console.log(purchase.purchasePlatform));
    });

ContextPlayer

Represents information about a player who is in the context that the current player is playing in.


Parameters

  • player PlayerData The player data for this context player.

getID( )

Get the id of the context player.

Returns string The ID of the context player


EndGamePayload

Class for formatting end game payloads for custom updates


APIErrorArgs

Arguments for creating an API Error.

Type: Object


Properties

  • code ErrorCodeType? The error code. Defaults to UNKNOWN if not provided.
  • message string A message describing the error.

APIError

An API Error returned by the Instant Games SDK


Parameters


code

The relevant error code

Type: ErrorCodeType


message

A message describing the error

Type: string


LiveMatchArgs

Arguments for creating a LiveMatch instance.

Type: Object


Properties

  • liveMatchID string The unique identifier for the live match
  • contextID string The context ID associated with this live match

LiveMatch

An instant game live match that is played in a Messenger Rooms call simultaneously by all the participants.


Parameters


getID( )

The unique live match ID.


Examples

FBInstant.room.getCurrentMatchAsync()
    .then(function(match) {
        console.log(match.getID());
    });

Returns string The live match ID


getContextID( )

The unique context ID that is associated with this live match.


Examples

FBInstant.room.getCurrentMatchAsync()
    .then(function(match) {
        console.log(match.getContextID());
    });

Returns string The context ID for this live match


AdInstanceData

Data structure representing an ad instance.

Type: Object


Properties

  • adInstanceID string Unique identifier for the ad instance
  • placementID string Audience Network placement ID for the ad

AdInstance

Represents an instance of an ad.


Parameters

  • data AdInstanceData The data for this ad instance
  • type AdType The type of ad (interstitial, rewarded video, etc.)

getPlacementID( )

Returns the Audience Network placement ID of this ad instance.

Returns string The placement ID for this ad


loadAsync( )

Preload the ad. The returned promise resolves when the preload completes, and rejects if it failed.


Examples

FBInstant.getInterstitialAdAsync(
    'my_placement_id',
).then(function(interstitial) {
    return interstitial.loadAsync();
}).then(function() {
    // Ad loaded
});
  • Throws ADS_FREQUENT_LOAD
  • Throws ADS_NO_FILL
  • Throws INVALID_PARAM
  • Throws NETWORK_FAILURE

Returns Promise A promise that resolves when the ad is successfully preloaded


showAsync( )

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.


Examples

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
});
  • Throws ADS_NOT_LOADED
  • Throws INVALID_PARAM
  • Throws NETWORK_FAILURE
  • Throws INVALID_OPERATION
  • Throws RATE_LIMITED
  • Throws USER_INPUT

Returns Promise A promise that resolves when the user has finished watching the ad


UpdateAction

Represents the type of the update action to perform.

Type: string


Properties

  • CUSTOM string A custom update, with all content specified by the game.

ContextData

Data structure representing a game context.

Type: Object


Properties

  • id string?? The unique identifier for this context
  • size number?? The number of participants in this context
  • type ContextType The type of context (e.g., SOLO, THREAD, GROUP)

ContextSizeResponse

Response object for context size checks. 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: Object


Properties

  • answer boolean Whether the context size is within the specified range
  • minSize number? The minimum size specified in the check
  • maxSize number? The maximum size specified in the check

GameContext

Represents the social context in which the game is being played. This class provides methods to access information about the current game context, such as its ID, type, and size (number of participants).


Parameters

  • context ContextData The context data to initialize with

getID( )

Returns the unique identifier for this context.

Returns (string | null) The context ID, or null if not available


getType( )

Returns the type of this context.

Returns ContextType The context type (e.g., SOLO, THREAD, GROUP)


getSize( )

Returns the number of participants in this context.

Returns (number | null) The context size, or null if not available


getContextSizeResponse( )

Returns the response from the last context size check.

Returns (ContextSizeResponse | null) The context size response, or null if no check has been performed


setContextSizeResponse( )

Sets the response for a context size check.


Parameters

Returns void


ContextFilter

A filter that may be applied to a Context Choose operation '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")


TournamentArgs

Arguments for creating a Tournament instance.

Type: Object


Properties

  • tournamentID string The unique identifier for the tournament.
  • contextID string The context ID associated with the tournament.
  • endTime number Timestamp when the tournament ends.
  • tournamentType InstantGameTimedLeaderboardTournamentExternalType The type of tournament.
  • title string? Optional title for the tournament.
  • payload string? Optional data payload for the tournament.

Tournament

An instant game tournament.


Parameters


getID( )

The unique ID that is associated with this instant tournament.


Examples

FBInstant.getTournamentAsync()
    .then(function(tournament) {
        console.log(tournament.getID());
    });

Returns string The unique tournament ID.


getContextID( )

The unique context ID that is associated with this instant tournament.


Examples

FBInstant.getTournamentAsync()
    .then(function(tournament) {
        console.log(tournament.getContextID());
    });

Returns string The unique context ID.


getEndTime( )

Timestamp when the instant tournament ends. If the end time is in the past, then the instant tournament is already finished and has expired.


Examples

FBInstant.getTournamentAsync()
    .then(function(tournament) {
        console.log(tournament.getEndTime());
    });

Returns number Unix timestamp when the tournament ends.


getTournamentType( )

Type of the tournament, eg default, page_hosted, daily, etc.


Examples

FBInstant.getTournamentAsync()
    .then(function(tournament) {
        console.log(tournament.getTournamentType());
    });

Returns InstantGameTimedLeaderboardTournamentExternalType The type of tournament.


getTitle( )

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.


Examples

FBInstant.getTournamentAsync()
    .then(function(tournament) {
        console.log(tournament.getTitle());
    })

Returns string? The title of the tournament, or null if none was provided.


getPayload( )

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.


Examples

FBInstant.getTournamentAsync()
    .then(function(tournament) {
        console.log(tournament.getPayload());
    })

Returns string? The payload data of the tournament, or null if none was provided.


GlobalLeaderboardEntry

Represents an entry in a global leaderboard.


Parameters


getScore( )

Returns the score of this leaderboard entry.

Returns number The score value


getPlayer( )

Returns the player associated with this leaderboard entry.

Returns GlobalLeaderboardPlayer The player object


OverlayViewError

Represents an error that occured during the lifecycle of an overlay view.

Type: Object


Properties

  • caller string Function that triggered the error (e.g. showAsync)
  • error mixed The specific error object that was thrown (e.g. APIError)

OverlayView

Represents an Instant Games overlay view.

Type: Object


Properties

  • id string The unique ID that is associated with this overlay view
  • iframeElement HTMLIFrameElement The iframe element for this overlay view that you can freely attach and position
  • initialData Object? The initial data that was passed to this overlay view on creation
  • onInitializedSuccessCallback function (OverlayView): void? The callback to be called when the view is successfully
  • onInitializedErrorCallback function (OverlayView, APIError): void? The callback to be called when an
  • status ShieldOverlayLifecycleState The current lifecycle state of the overlay view
  • errors Array<OverlayViewError> List of errors that occurred during the lifecycle of this overlay view
  • showAsyncPromiseHandlerData AsyncPromiseHandlerData Data for managing the state of the showAsync promise
  • updateAsyncPromiseHandlerData AsyncPromiseHandlerData Data for managing the state of the updateAsync promise
  • dismissAsyncPromiseHandlerData AsyncPromiseHandlerData Data for managing the state of the dismissAsync promise

getID( )

The unique ID that is associated with this overlay view.

Returns string The unique identifier for this overlay view


getIFrameElement( )

The iframe element for this overlay view that you can freely attach and position in your DOM tree

Returns HTMLIFrameElement The iframe element for this overlay view


getStatus( )

Status of the overlay view.

Returns ShieldOverlayLifecycleState The current lifecycle state of the overlay view


getInitialData( )

Initial data that was passed in to this overlay view on creation

Returns Object? The initial data passed to this overlay view, or null if none was provided


getErrors( )

List of errors that occurred during the lifecycle of this overlay view

Returns Array<OverlayViewError> Array of errors that occurred during the lifecycle of this overlay view


showAsync( )

Call this method to show the overlay view after you attach it to your DOM tree.

Returns Promise A promise that resolves when the overlay view is shown


updateAsync( )

Call this method to update the overlay view with new data. You still need to call showAsync() on the overlay view in order to display the new data.


Parameters

  • updatedData Object The data to be passed to the overlay view

Returns Promise A promise that resolves when the update is complete, otherwise rejects with an APIError. Note that you would still have to call showAsync() on the overlay view in order to display it


dismissAsync( )

Call this method to hide the overlay view.

Returns Promise A promise that resolves when the overlay view is hidden


Platform

Represents the current platform that the user is playing on.

Type: ("IOS" | "ANDROID" | "WEB" | "MOBILE_WEB")


ErrorCode

Error codes that may be returned by the Instant Games API

Type: string


Properties

  • 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 above
  • CLIENT_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.
  • OPERATION_SUPPRESSED string The operation was suppressed by the platform. This may be due to user-level rate limiting, play style restrictions, or other reasons.
  • GLOBAL_LEADERBOARD_NOT_FOUND string No global leaderboard with the requested ID was found. Either the leaderboard does not exist yet, or the ID did not match any registered leaderboard, you can verify the leaderboard ID in the Global Leaderboard section of the Instant Games Dashboard.
  • IARC_CERT_NOT_FOUND string The requested IARC (International Age Rating Coalition) certificate was not found.
  • IARC_CERT_TEST_ONLY string This is a test IARC (International Age Rating Coalition) operation.
  • IARC_SUBMIT_CERT_FAILED string Thw IARC (International Age Rating Coalition) certificate failed to be submitted.
  • IARC_SUBMIT_EMAIL_FAILED string The developer's IARC (International Age Rating Coalition) contact email failed to be submitted.
  • 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.
  • MOCK_IAP string User is temporarily turning off Mock IAP and switching to production flow for current purchase
  • 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.
  • TOURNAMENT_NOT_SHAREABLE string The game attempted to share a private tournament. This is only possible for non-private tournaments. If a score was submitted with the share call, then the score was still submitted.
  • 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.

Examples

FBInstant.startGameAsync().catch(function(e) {
    console.log(e);
});
// {code: 'CLIENT_UNSUPPORTED_OPERATION', message: '...'}

ErrorCodeType

An Instant Games error code, one of ErrorCode

Type: string


ShareWithOverlayPayload

Represents content to be shared by the user.

Type: Object


Properties

  • intent ("INVITE" | "REQUEST" | "CHALLENGE" | "SHARE") Indicates the intent of the share.
  • image string? Optional, but must be specified if imageOverlayPath is not specified.
  • imageOverlayPath string? A path relative from the root of the game to the XML that represents the image to be shared. Optional, but must be specified if the image property is not specified.
  • pathToCSS string? A path to the CSS from index.html used for classes in the XML. Optional, but necessary if className is used in the imageOverlay XML.
  • initialData Object? A blob of data used in the text or in the imageOverlay XML. Optional, but necessary if either the text or imageOverlay uses developer parameters.
  • media MediaParams? Optional content for the gif or video.
  • text string A text message to be shared. Can use the same user data and developer parameter keys that the overlays use.
  • notificationText string? A text message to be used for notifications when sharing using to separate user message and notifcation text. If not included we will use the default text property for sharing in messenger and the notification.
  • 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().
  • shareDestination Array<ShareDestination>? A optional array to set sharing destinations in the share dialog.If not specified all available sharing destinations will be displayed.
  • surface ("FACEBOOK" | "MESSENGER" | "WHATSAPP")? Optional property to specify the surface where the share will be posted.
  • switchContext boolean? A flag indicating whether to switch the user into the new context created on sharing

MediaContent

Defines the structure for media content references.

Type: Object


Properties

  • url string URL pointing to the media asset stored on the developer's server.

MediaParams

Represents the media payload used by custom update and custom share.

Type: Object


Properties

  • gif MediaContent? If provided, contains information for retrieving a GIF media asset.
  • video MediaContent? If provided, contains information for retrieving a video media asset.

ShareDestination

A parameter that may be applied to a shareAsync operation. This sets up sharing destinations in the share dialog.

Possible values:

  • 'NEWSFEED': Enable share to newsfeed option
  • 'GROUP': Enable share to official game group option. This is only available for games with official game group. To set up official game group, add a page in the game app setting in https://www.developers.facebook.com, and then create a group for the page in https://facebook.com.
  • 'COPY_LINK': Enable copy the game link in clipboard
  • 'MESSENGER': Enable share game to messenger option

Type: string


Product

Represents a game's product information.

Type: Object


Properties

  • title string The title of the product
  • productID string The product's game-specified identifier
  • description string? The product description
  • imageURI string? A link to the product's associated image
  • price string The price of the product
  • priceCurrencyCode string The currency code for the product
  • priceAmount number The numeric price of a product

Purchase

Represents an individual purchase of a game product.

Type: Object


Properties

  • developerPayload string? A developer-specified string, provided during the purchase of the product
  • isConsumed boolean Whether or not the purchase has been consumed
  • paymentActionType string The current status of the purchase, such as 'charge' or 'refund'
  • paymentID string The identifier for the purchase transaction
  • productID string The product's game-specified identifier
  • purchasePlatform PurchasePlatform The platform associated with the purchase, such as "FB" for Facebook and "GOOGLE" for Google.
  • purchasePrice Object Contains the local amount and currency associated with the purchased item
  • purchaseTime string Unix timestamp of when the purchase occurred
  • purchaseToken string A token representing the purchase that may be used to consume the purchase
  • signedRequest SignedPurchaseRequest Server-signed encoding of the purchase request

SignedPurchaseRequest

Type: string


Examples

Eii6e636mz5J47sfqAYEK40jYAwoFqi3x5bxHkPG4Q4.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImlzc3VlZF9hdCI6MTUwMDM5ODY3NSwicGxheWVyX2lkIjoiMTI0OTUyNTMwMTc1MjIwMSIsInJlcXVlc3RfcGF5bG9hZCI6Im15X2ZpcnN0X3JlcXVlc3QifQ

PurchaseConfig

The configuration of a purchase request for a product registered to the game.

Type: Object


Properties

  • productID string The identifier of the product to purchase
  • developerPayload string? An optional developer-specified payload, to be included in the returned purchase's signed request.

InviteWithOverlayPayload

Represents content to be shared in invites sent by the user.

Type: Object


Properties

  • image string? Optional, but must be specified if imageOverlayPath is not specified.
  • imageOverlayPath string? A path relative from the root of the game to the XML that represents the image to be shared. Optional, but must be specified if the image property is not specified.
  • pathToCSS string? A path to the CSS from index.html used for classes in the XML. Optional, but necessary if className is used in the imageOverlay XML.
  • initialData Object? A blob of data used in the text or in the imageOverlay XML. Optional, but necessary if either the text or imageOverlay uses developer parameters.
  • 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'. Can use the same user data and developer parameter keys that the overlays use.
  • notificationText (string? | LocalizableContent?) A notification message, or an object with the default notification text as the value of 'default' and another object mapping locale keys to translations as the value of 'localizations'. This value will be used to separate message (see text parameter) and notifcation text. If not included we will use the text property for sending message in messenger and notification.
  • 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'.
  • dialogTitle (string? | LocalizableContent?) An optional title to display at the top of the invite dialog instead of the generic title. This param is not sent as part of the message, but only displays in the dialog header. The title can be either a string 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().
  • filters Array<InviteFilter>? The set of filters to apply to the suggestions. Multiple filters may be applied. If no results are returned when the filters are applied, the results will be generated without the filters.
  • sections Array<InviteSection>? The set of sections to be included in the dialog. Each section can be assigned a maximum number of results to be returned (up to a maximum of 10). If no max is included, a default max will be applied. Sections will be included in the order they are listed in the array. The last section will include a larger maximum number of results, and if a maxResults is provided, it will be ignored. If this array is left empty, default sections will be used.

InviteFilter

A filter that may be applied to an inviteAsync operation. If no results are returned with the filters, then the filters will not be applied. 'NEW_CONTEXT_ONLY' - Prefer to only surface contexts the game has not been played in before. This can include players who have not played the game before. 'NEW_PLAYERS_ONLY' - Prefer to only surface people who have not played the game before. 'EXISTING_CONTEXT_ONLY' - Prefer to only surface contexts the game has been played in before. 'EXISTING_PLAYERS_ONLY' - Prefer to only surface people who have played the game before.

Type: ("NEW_CONTEXT_ONLY" | "NEW_PLAYERS_ONLY" | "EXISTING_CONTEXT_ONLY" | "EXISTING_PLAYERS_ONLY")


InviteSection

Represents a section in the inviteAsync dialog that contains suggested matches. The sections will be shown in the order they are included in the array, and the last section will contain as many results as possible.

Type: Object


Properties

  • sectionType InviteSectionType The type of section to include in the inviteAsync dialog
  • maxResults number? Optional maximum number of results to include in the section. This can be no higher than 10. This will be disregarded for the last section, which will contain as many results as possible. If not included, the default maximum number of results for that section type will be used.

InviteSectionType

Represents the type of section to include. All section types may include both new and existing contexts and players.

Type: string


Properties

  • GROUPS string This contains group contexts, such as contexts from group threads.
  • USERS string This contains individual users, such as friends or 1:1 threads.

LocalizableContent

Represents a string with localizations and a default value to fall back on.

Type: Object


Properties


CustomUpdateWithOverlayPayload

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


Properties

  • 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][67] 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. Must be specified if imageOverlayPath or media are not specified.
  • imageOverlayPath string? Optional path to the XML that represents the image to be shared. Must be specified if image or media are not specified.
  • pathToCSS string? A path to the CSS from index.html used for classes in the XML. Optional, but necessary if className is used in the imageOverlay XML.
  • initialData Object? A blob of data used in the text or in the imageOverlay XML. Optional, but necessary if either the text or imageOverlay uses developer parameters.
  • 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'. Can use the same user data and developer parameter keys that the overlays use.
  • notificationText (string? | LocalizableContent?) A notification message, or an object with the default notification text as the value of 'default' and another object mapping locale keys to translations as the value of 'localizations'. This value will be used to separate message (see text parameter) and notification text. If not included we will use the text property for sending a message in messenger and notification.
  • 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. 'IMMEDIATE_CLEAR' - The update is posted immediately, and clears any other pending updates (such as those sent with the 'LAST' strategy). 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.

CreateTournamentConfig

Represents the configurations used in creating an Instant Tournament

Type: Object


Properties

  • title string? Optional text title for the tournament, please do not include user names in title.
  • forceScoreValidation boolean? Optional boolean that specifies if the tournament requires game server validation before a score can be added to or updated on the leaderboard.
  • image string? Optional base64 encoded image that will be associated with the tournament and included in posts sharing the tournament
  • sortOrder 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.
  • forceScoreRangeValidation boolean? Optional boolean that specifies if the tournament should use score range validation. If true, then minimum and/or maximum scores should be provided; scores falling outside the range will be automatically rejected. If either minimum or maximum is null, then that side of the range will be ignored.
  • minimumScore number? Optional input will only be used if forceScoreRangeValidation is true. If it is, scores below this will be automatically rejected. If null or forceScoreRangeValidation is false, no minimum will be used
  • maximumScore number? Optional input will only be used if forceScoreRangeValidation is true. If it is, scores above this will be automatically rejected. If null or forceScoreRangeValidation is false, no maximum will be used
  • tournamentType string? Optional input for tournament type. This can be set to either "COLLABORATIVE" (everyone works together for a goal) or "DEEP" (the standard tournaments). This will default to "DEEP" if no value is provided.
  • goal integer? Input for collaborative tournaments, participants strive to reach this goal to beat the tournament. This input is optional for standard tournaments and required for collaborative tournaments.

CreateTournamentPayload

Represents content used to create an Instant Tournament

Type: Object


Properties

  • initialScore number An integer value representing the player's score which will be the first score in the tournament.
  • config CreateTournamentConfig An object holding optional configurations for the tournament
  • data GamePayload? 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.

ShareTournamentPayload

Represents content used to reshare an Instant Tournament.

Type: Object


Properties

  • score number An optional 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.