API Reference v5.0


Changelog

  1. Ad APIs Two new APIs for running Interstitial and Rewarded Video Ads. Requires game to be configured for Ads on Instant Games.
  2. Player Stats API to set, get, and atomically increment integer stats associated with the player. This is complemented by new additions to the Bundle Config, which allow configuring metadata for player stats in order to surface stats through Facebook platform-level integrations.
  3. getEntryPointAsync API to get the entry point from which the game was launched.
  4. Custom Update Dev Localization Addition to the Custom Update API, allowing developers to provide localizations of the update content.
  5. Breaking Change Rename CLIENT_REQUIRES_UPDATE to CLIENT_UNSUPPORTED_OPERATION

FBInstant

Top level namespace for the Instant Games SDK.


player

Contains functions and properties related to the current player.


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? A unique identifier for the player.


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? 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<SignedPlayerInfo> A promise that resolves with a #signedplayerinfo object.


getName( )

The player's localized display name. This function should not be called until FBInstant.startGameAsync() has resolved.

Examples

// This function should be called after FBInstant.startGameAsync()
// resolves.
var playerName = FBInstant.player.getName();

Returns string? The player's localized display name.


getPhoto( )

A url to the player's public profile photo. The photo will always be a square, and with dimensions of at least 200x200. When rendering it in the game, the exact dimensions should never be assumed to be constant. It's recommended to always scale the image to a desired size before rendering. The value will always be null until FBInstant.startGameAsync() resolves.

WARNING: Due to CORS, using these photos in the game canvas can cause it to be tainted, which will prevent the canvas data from being extracted. To prevent this, set the cross-origin attribute of the images you use to 'anonymous'.

Examples

var playerImage = new Image();
playerImage.crossOrigin = 'anonymous';
// This function should be called after FBInstant.startGameAsync()
// resolves.
playerImage.src = FBInstant.player.getPhoto();

Returns string? Url to the player's public profile photo.


getDataAsync( )

Retrieve data from the designated cloud storage of the current player.

Parameters

  • keys Array<string> 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<Object> A promise that resolves with an object which contains the current key-value pairs for each key specified in the input array, if they exist.


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 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 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 A promise that resolves when changes have been persisted successfully, and rejects if the save fails.


getStatsAsync( )

Retrieve stats from the designated cloud storage of the current player.

Parameters

  • keys Array<string>? An optional array of unique keys to retrieve stats for. If the function is called without it, it will fetch all stats.

Examples

FBInstant.player
  .getStatsAsync(['level', 'zombiesSlain'])
  .then(function(stats)) {
    console.log('stats are loaded');
    var level = data['level'];
    var zombiesSlain = data['zombiesSlain'];
  });
  • Throws INVALID_PARAM
  • Throws NETWORK_FAILURE
  • Throws CLIENT_UNSUPPORTED_OPERATION

Returns Promise<Object> A promise that resolves with an object which contains the current key-value pairs for each key specified in the input array, if they exist.


setStatsAsync( )

Set stats to be saved to the designated cloud storage of the current player.

Parameters

  • stats Object An object containing a set of key-value pairs that should be persisted to cloud storage as stats, which can be surfaced or used in a variety of ways to benefit player engagement. The object must contain only numerical values - any non-numerical values will cause the entire modification to be rejected.

Examples

FBInstant.player
  .setStatsAsync({
    level: 5,
    zombiesSlain: 27,
  })
  .then(function() {
    console.log('data is set');
  });
  • Throws INVALID_PARAM
  • Throws NETWORK_FAILURE
  • Throws PENDING_REQUEST
  • Throws CLIENT_UNSUPPORTED_OPERATION

Returns Promise A promise that resolves when the input values are set. NOTE: The promise resolving does not necessarily mean that the input has already been persisted. Rather, it means that the data was validated and has been scheduled to be saved. It also guarantees that all values that were set are now available in player.getStatsAsync.


incrementStatsAsync( )

Increment stats saved in the designated cloud storage of the current player.

Parameters

  • increments Object An object containing a set of key-value pairs indicating how much to increment each stat in cloud storage. The object must contain only numerical values - any non-numerical values will cause the entire modification to be rejected.

Examples

FBInstant.player
  .incrementStatsAsync({
    level: 1,
    zombiesSlain: 17,
    rank: -1,
  })
 .then(function(stats)) {
    console.log('increments have been made! New values');
    var level = data['level'];
    var zombiesSlain = data['zombiesSlain'];
  });
  • Throws INVALID_PARAM
  • Throws NETWORK_FAILURE
  • Throws PENDING_REQUEST
  • Throws CLIENT_UNSUPPORTED_OPERATION

Returns Promise<Object> A promise that resolves with an object which contains the updated key-value pairs for each key specified in the input dictionary. NOTE: The promise resolving does not necessarily mean that the changes have already been persisted. Rather, it means that the increments were valid and have been scheduled to be performed. It also guarantees that all values that were incremented are now available in player.getStatsAsync.


getConnectedPlayersAsync( )

Fetches an array of ConnectedPlayer objects containing information about players that are connected to the current player.

NOTE: This promise will not resolve until FBInstant.startGameAsync() has resolved.

Examples

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

Returns Promise<Array<ConnectedPlayer>> A promise that resolves with a list of connected player objects.


context

Contains functions and properties related to the current game context.


getID( )

A unique identifier for the current game context. This represents a specific context that the game is being played in (for example, a particular messenger conversation or 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.startGameAsync()
// resolves.
var contextID = FBInstant.context.getID();

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


getType( )

The type of the current game context.

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

Examples

// This function should be called after FBInstant.startGameAsync()
// resolves.
var contextType = FBInstant.context.getType();

Returns ("POST" | "THREAD" | "GROUP" | "SOLO") Type of the current game context.


isSizeBetween( )

This function determines whether the number of participants in the current game context is between a given minimum and maximum, inclusive. If one of the bounds is null only the other bound will be checked against. It will always return the original result for the first call made in a context in a given game play session. Subsequent calls, regardless of arguments, will return the answer to the original query until a context change occurs and the query result is reset.

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

This will be null if one or both of the supplied arguments are not valid, if we do not have a size available for the current context, or if the API is called before startGameAsync() resolves.

Parameters

  • minSize number? The minimum bound of the context size query.
  • minSize number? The maximum bound of the context size query.
  • maxSize number?

Examples

console.log(FBInstant.context.isSizeBetween(3, 5)); (Context size = 4)
// {answer: true, minSize: 3, maxSize: 5}
console.log(FBInstant.context.isSizeBetween(5, 7)); (Context size = 4)
// {answer: false, minSize: 5, maxSize: 7}
console.log(FBInstant.context.isSizeBetween(2, 10)); (Context size = 3)
// {answer: true, minSize: 2, maxSize: 10}
console.log(FBInstant.context.isSizeBetween(4, 8)); (Still in same context)
// {answer: true, minSize: 2, maxSize: 10}
console.log(FBInstant.context.isSizeBetween(3, null)); (Context size = 4)
// {answer: true, minSize: 3, maxSize: null}
console.log(FBInstant.context.isSizeBetween(null, 3)); (Context size = 4)
// {answer: false, minSize: null, maxSize: 3}
console.log(FBInstant.context.isSizeBetween("test", 5)); (Context size = 4)
// null
console.log(FBInstant.context.isSizeBetween(0, 100)); (Context size = null)
// null

Returns ContextSizeResponse?


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 ID of the desired context.

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 A promise that resolves when the game has switched into the specified context, or rejects otherwise.


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? An object specifying conditions on the contexts that should be offered.
  • options.filters Array<ContextFilter>? The set of filters to apply to the context suggestions.
  • options.maxSize number? The maximum number of participants that a suggested context should ideally have.
  • options.minSize number? The minimum number of participants that a suggested context should ideally have.

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 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).


createAsync( )

Attempts to create or switch into a context between a specified player and the current player. The returned promise will reject if the player listed is not a Connected Player of the current player or if the player does not provide permission to enter the new context. Otherwise, the promise will resolve when the game has switched into the new context.

Parameters

  • playerID string ID of the player

Examples

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

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


getPlayersAsync( )

Gets an array of #contextplayer objects containing information about active players (people who played the game in the last 90 days) that are associated with the current context. This may include the current player.

NOTE: This promise will not resolve until FBInstant.startGameAsync() has resolved.

Examples

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

Returns Promise<Array<ContextPlayer>>


getLocale( )

The current locale. Use this to determine what language the current game should be localized with. The value will not be accurate until FBInstant.startGameAsync() resolves.

Examples

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

Returns string? 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?


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 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 A promise that resolves when the SDK is ready to use.


setLoadingProgress( )

Report the game's initial loading progress.

Parameters

  • percentage number 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<string> 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.startGameAsync() resolves.

Examples

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

Returns Object? Data associated with the current entry point.


getEntryPointAsync( )

Returns the entry point that the game was launched from

Examples

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

Returns string The name of the entry point from which the user started the game


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 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 A promise that resolves when the game should start.


shareAsync( )

This invokes a dialog to let the user share specified content, either as a message in Messenger or as a post on the user's timeline. 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 SharePayload Specify what to share. See example for details.

Examples

FBInstant.shareAsync({
  intent: 'REQUEST',
  image: base64Picture,
  text: 'X is asking for your help!',
  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 A promise that resolves when the share is completed or cancelled.


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

Examples

// This will post a custom update. If the game is played in a messenger
// chat thread, this will post a message into the thread with the specified
// image and text message. And when people launch the game from this
// message, those game sessions will be able to access the specified blob
// of data through FBInstant.getEntryPointData().
FBInstant.updateAsync({
  action: 'CUSTOM',
  cta: 'Join The Fight',
  image: base64Picture,
  text: {
    default: 'X just invaded Y\'s village!',
    localizations: {
      ar_AR: 'X \u0641\u0642\u0637 \u063A\u0632\u062A ' +
      '\u0642\u0631\u064A\u0629 Y!',
      en_US: 'X just invaded Y\'s village!',
      es_LA: '\u00A1X acaba de invadir el pueblo de Y!',
    }
  }
  template: 'VILLAGE_INVASION',
  data: { myReplayData: '...' },
  strategy: 'IMMEDIATE',
  notification: 'NO_PUSH',
}).then(function() {
  // closes the game after the update is posted.
  FBInstant.quit();
});
  • Throws INVALID_PARAM
  • Throws PENDING_REQUEST

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


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 for more details about FB Analytics.

Parameters

  • eventName string Name of the event. Must be 2 to 40 characters, and can only contain '_', '-', ' ', and alphanumeric characters.
  • valueToSum number An optional numeric value that FB Analytics can calculate a sum with.
  • parameters Object An optional object that can contain up to 25 key-value pairs to be logged with the event. Keys must be 2 to 40 characters, and can only contain '_', '-', ' ', and alphanumeric characters. Values must be less than 100 characters in length.

Examples

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

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


onPause( )

Set a callback to be fired when a pause event is triggered.

Parameters

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

Returns void


getInterstitialAdAsync( )

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

Parameters

  • placementID string 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 A promise that resolves with a #adinstance, or rejects with a #apierror 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 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 A promise that resolves with a #adinstance, or rejects with a #apierror if it couldn't be created.


LocalizationsDict

Represents a mapping from locales to translations of a given string. Each property is an optional five-character Facebook locale code of the form xx_XX. See https://www.facebook.com/translations/FacebookLocales.xml for a complete list of supported locale codes.

Type: Object


APIError

An API Error returned by the Instant Games SDK


code

The relevant error code

Type: ErrorCodeType


message

A message describing the error

Type: string


SignedPlayerInfo

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


getPlayerID( )

Get the id of the player.

Returns string 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 4 steps:

  • Split the signature into two parts delimited by the '.' character.
  • Decode the first part (the encoded signature) with base64url encoding.
  • 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.
  • Hash the whole response payload string using HMAC SHA-256 and your app secret and confirm that it is equal to the encoded signature.
  • 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

Eii6e636mz5J47sfqAYEK40jYAwoFqi3x5bxHkPG4Q4.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImlzc3VlZF9hdCI6MTUwMDM5ODY3NSwicGxheWVyX2lkIjoiMTI0OTUyNTMwMTc1MjIwMSIsInJlcXVlc3RfcGF5bG9hZCI6Im15X2ZpcnN0X3JlcXVlc3QifQ

Returns string The signature string.


ConnectedPlayer

Represents information about a player who is connected to the current player.


getID( )

Get the id of the connected player.

Returns string The ID of the connected player


getName( )

Get the player's full name.

Returns string? The player's full name


getPhoto( )

Get the player's public profile photo.

Returns string? A url to the player's public profile photo


ContextPlayer

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


getID( )

Get the id of the context player.

Returns string The ID of the context player


getName( )

Get the player's localized display name.

Returns string? The player's localized display name.


getPhoto( )

Get the player's public profile photo.

Returns string? A url to the player's public profile photo


AdInstance

Represents an instance of an ad.


getPlacementID( )

Return the Audience Network placement ID of this ad instance.


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


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

Returns Promise


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")


Platform

Represents the current platform that the user is playing on.

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


ContextSizeResponse

The answer field is true if the current context size is between the minSize and maxSize values that are specified in the object, and false otherwise.

Type: {answer: boolean, minSize: number?, maxSize: number?}


SharePayload

Represents content to be shared by the user.

Type: Object

Properties

  • intent ("INVITE" | "REQUEST" | "CHALLENGE" | "SHARE") Indicates the intent of the share.
  • image string A base64 encoded image to be shared.
  • text string A text message to be shared.
  • data Object? A blob of data to attach to the share. All game sessions launched from the share will be able to access this blob through FBInstant.getEntryPointData().

ErrorCode

Error codes that may be returned by the Instant Games API

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.
  • 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).
  • 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.
  • 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.
  • SAME_CONTEXT string The game attempted to perform a context switch into the current context.
  • UNKNOWN string An unknown or unspecified issue occurred. This is the default error code returned when the client does not specify a code.
  • USER_INPUT string The user made a choice that resulted in a rejection. For example, if the game calls up the Context Switch dialog and the player closes it, this error code will be included in the promise rejection.

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


CustomUpdatePayload

Represents a custom update for FBInstant.updateAsync.

Type: Object

Properties

  • action string For custom updates, this should be 'CUSTOM'.
  • template string ID of the template this custom update is using. Templates should be predefined in fbapp-config.json. See the [Bundle Config documentation]https://developers.facebook.com/docs/games/instant-games/bundle-config for documentation about fbapp-config.json.
  • cta (string? | LocalizableContent?) Optional call-to-action button text. By default we will use a localized 'Play' as the button text. To provide localized versions of your own call to action, pass an object with the default cta as the value of 'default' and another object mapping locale keys to translations as the value of 'localizations'.
  • image string Data URL of a base64 encoded image.
  • text (string | LocalizableContent) A text message, or an object with the default text as the value of 'default' and another object mapping locale keys to translations as the value of 'localizations'.
  • data Object? A blob of data to attach to the update. All game sessions launched from the update will be able to access this blob through FBInstant.getEntryPointData(). Must be less than or equal to 1000 characters when stringified.
  • strategy string? Specifies how the update should be delivered. This can be one of the following: 'IMMEDIATE' - The update should be posted immediately. 'LAST' - The update should be posted when the game session ends. The most recent update sent using the 'LAST' strategy will be the one sent. '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.

LocalizableContent

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

Type: Object

Properties