YouTube Playables SDK reference


ytgame

The top-level namespace for the YouTube Playables SDK.

This is a globally scoped variable in the current window. You MUST NOT override this variable.
Namespaces
ads
🧪 PUBLIC PREVIEW API: SUBJECT TO CHANGE WITHOUT NOTICE.
engagement
The functions and properties related to player engagement.
game
The functions and properties related to generic game behaviors.
health
The functions and properties related to the game health.
system
The functions and properties related to the YouTube system.
Enumerations
SdkErrorType
The types of errors that the YouTube Playables SDK throws.
Classes
SdkError
The error object that the YouTube Playables SDK throws.
Variables
IN_PLAYABLES_ENV
Whether or not the game is running within the Playables environment.
SDK_VERSION
The YouTube Playables SDK version.
See also

Enumerations


Const SdkErrorType

SdkErrorType
The types of errors that the YouTube Playables SDK throws.
Enumeration Members
API_UNAVAILABLE
The API was temporarily unavailable.

Ask players to retry at a later time if they are in a critical flow.
INVALID_PARAMS
The API was called with invalid parameters.
SIZE_LIMIT_EXCEEDED
The API was called with parameters exceeding the size limit.
UNKNOWN
The error type is unknown.

Variables


Const IN_PLAYABLES_ENV

IN_PLAYABLES_ENV: boolean
Whether or not the game is running within the Playables environment. You can use this to determine whether to enable or disable features that are only available inside of Playables. Combine this check with checking for ytgame to ensure that the SDK is actually loaded.
Example
const inPlayablesEnv = typeof ytgame !== "undefined" && ytgame.IN_PLAYABLES_ENV;
// An example of where you may want to fork behavior for saving data.
if (ytgame?.IN_PLAYABLES_ENV) {
  ytgame.game.saveData(dataStr);
} else {
  window.localStorage.setItem("SAVE_DATA", dataStr);
}

Const SDK_VERSION

SDK_VERSION: string
The YouTube Playables SDK version.
Example
// Prints the SDK version to console. Do not do this in production.
console.log(ytgame.SDK_VERSION);

ytgame.SdkError

Extends Error
The error object that the YouTube Playables SDK throws.

The SdkError object is a child of Error and contains an additional field.
Constructors
constructor
Properties
errorType
The type of the error.
message
name
stack?

Properties


errorType

errorType: SdkErrorType
The type of the error.

ytgame.ads

🧪 PUBLIC PREVIEW API: SUBJECT TO CHANGE WITHOUT NOTICE.

The functions and properties related to ads.
Functions
requestInterstitialAd
Requests an interstitial ad to be shown.

Functions


requestInterstitialAd

requestInterstitialAd(): Promise<void>
Experimental Requests an interstitial ad to be shown.

🧪 PUBLIC PREVIEW API: SUBJECT TO CHANGE WITHOUT NOTICE.

Makes no guarantees about whether the ad was shown.
Example
try {
  await ytgame.ads.requestInterstitialAd();
  // Ad request successful, do something else.
} catch (error) {
  // Handle errors, retry logic, etc.
  // Note that error may be undefined.
}
Returns
Promise<void> a promise that resolves on a successful request or rejects/throws on an unsuccessful request.

ytgame.engagement

The functions and properties related to player engagement.
Interfaces
Content
The content object the game sends to YouTube.
Score
The score object the game sends to YouTube.
Functions
openYTContent
Requests YouTube to open content corresponding to the provided video ID.
sendScore
Sends a score to YouTube.

Functions


openYTContent

openYTContent(content: Content): Promise<void>
Requests YouTube to open content corresponding to the provided video ID.

Generally, this will open the video in a new tab on web and in the miniplayer on mobile.
Example
async function showVideo(videoID: string) {
  try {
    await ytgame.engagement.openYTContent({ id: videoID });
    // Request successful, do something else.
  } catch (error) {
    // Handle errors, retry logic, etc.
    // Note that error may be undefined.
  }
}
Parameters
content: Content the content to open on YouTube.
Returns
Promise<void> a Promise that resolves when succeeded and rejects/throws with an ytgame.SdkError when failed.

sendScore

sendScore(score: Score): Promise<void>
Sends a score to YouTube.

The score should represent one dimension of progress within the game. If there are multiple dimensions, the developer must choose one dimension to be consistent. Scores will be sorted and the highest score will be displayed in YouTube UI so any in-game high score UI should align with what is being sent through this API.
Example
async function onScoreAwarded(score: number) {
  try {
    await ytgame.engagement.sendScore({ value: score });
    // Score sent successfully, do something else.
  } catch (error) {
    // Handle errors, retry logic, etc.
    // Note that error may be undefined.
  }
}
Parameters
score: Score the score to send to YouTube.
Returns
Promise<void> a Promise that resolves when succeeded and rejects/throws with an ytgame.SdkError when failed.

ytgame.engagement.Content

The content object the game sends to YouTube.
Properties
id
The ID of the video we want to open.

Properties


id

id: string
The ID of the video we want to open.

ytgame.engagement.Score

The score object the game sends to YouTube.
Properties
value
The score value expressed as an integer.

Properties


value

value: number
The score value expressed as an integer. The score must be less than or equal to the maximum safe integer. Otherwise, the score will be rejected.

ytgame.game

The functions and properties related to generic game behaviors.
Functions
firstFrameReady
Notifies YouTube that the game has begun showing frames.
gameReady
Notifies YouTube that the game is ready for players to interact with.
loadData
Loads game data from YouTube in the form of a serialized string.
saveData
Saves game data to the YouTube in the form of a serialized string.

Functions


firstFrameReady

firstFrameReady(): void
Notifies YouTube that the game has begun showing frames.

The game MUST call this API. Otherwise, the game is not shown to users. firstFrameReady() MUST be called before gameReady().
Example
function onGameInitialized() {
  ytgame.game.firstFrameReady();
}

gameReady

gameReady(): void
Notifies YouTube that the game is ready for players to interact with.

The game MUST call this API when it is interactable. The game MUST NOT call this API when a loading screen is still shown. Otherwise, the game fails the YouTube certification process.
Example
function onGameInteractable() {
  ytgame.game.gameReady();
}

loadData

loadData(): Promise<string>
Loads game data from YouTube in the form of a serialized string.

The game must handle any parsing between the string and an internal format.
Example
async function gameSetup() {
  try {
    const data = await ytgame.game.loadData();
    // Load succeeded, do something with data.
  } catch (error) {
    // Handle errors, retry logic, etc.
    // Note that error may be undefined.
  }
}
Returns
Promise<string> a Promise that completes when loading succeeded and rejects with an ytgame.SdkError when failed.

saveData

saveData(data: string): Promise<void>
Saves game data to the YouTube in the form of a serialized string.

The string must be a valid, well-formed UTF-16 string and a maximum of 3 MiB. The game must handle any parsing between the string and an internal format. If necessary, use String.isWellFormed() to check if the string is well-formed.
Example
async function saveGame() {
  try {
    ytgame.game.saveData(JSON.stringify(gameSave));
    // Save succeeded.
  } catch (error) {
    // Handle errors, retry logic, etc.
    // Note that error may be undefined.
  }
}
Parameters
data: string
Returns
Promise<void> a Promise that resolves when saving succeeded and rejects with an ytgame.SdkError when failed.

ytgame.health

The functions and properties related to the game health.
Functions
logError
Logs an error to YouTube.
logWarning
Logs a warning to YouTube.

Functions


logError

logError(): void
Logs an error to YouTube.

Note: This API is best-effort and rate-limited which can result in data loss.
Example
function onError() {
  ytgame.health.logError();
}

logWarning

logWarning(): void
Logs a warning to YouTube.

Note: This API is best-effort and rate-limited which can result in data loss.
Example
function onWarning() {
  ytgame.health.logWarning();
}

ytgame.system

The functions and properties related to the YouTube system.
Functions
getLanguage
Returns the language that is set in the user's YouTube settings in the form of a BCP-47 language tag.
isAudioEnabled
Returns whether the game audio is enabled in the YouTube settings.
onAudioEnabledChange
Sets a callback to be triggered when the audio settings change event is fired from YouTube.
onPause
Sets a callback to be triggered when a pause game event is fired from YouTube.
onResume
Sets a callback to be triggered when a resume game event is fired from YouTube.

Functions


getLanguage

getLanguage(): Promise<string>
Returns the language that is set in the user's YouTube settings in the form of a BCP-47 language tag.
Example
const localeTag = await ytgame.system.getLanguage();
// `localeTag` is now set to something like "en-US" or "es-419".
Returns
Promise<string> a Promise that completes when getting the language succeeded and rejects with an ytgame.SdkError when failed.

isAudioEnabled

isAudioEnabled(): boolean
Returns whether the game audio is enabled in the YouTube settings.

The game SHOULD use this to initialize the game audio state.
Example
function initGameSound() {
  if (ytgame.system.isAudioEnabled()) {
    // Enable game audio.
  } else {
    // Disable game audio.
  }
}
Returns
boolean a boolean indicating whether the audio is enabled.

onAudioEnabledChange

onAudioEnabledChange(callback: ((isAudioEnabled: boolean) => void)): (() => void)
Sets a callback to be triggered when the audio settings change event is fired from YouTube.

The game MUST use this API to update the game audio state.
Example
ytgame.system.onAudioEnabledChange((isAudioEnabled) => {
  if (isAudioEnabled) {
    // Enable game audio.
  } else {
    // Disable game audio.
  }
});
Parameters
callback: ((isAudioEnabled: boolean) => void) the callback function to be triggered.
Returns
(() => void) a function to unset the callback that is usually unused.

onPause

onPause(callback: (() => void)): (() => void)
Sets a callback to be triggered when a pause game event is fired from YouTube. The game has a short window to save any state before it is evicted.

onPause is called for all types of pauses, including when the user exits the game. There is no guarantee that the game will resume.
Example
ytgame.system.onPause(() => {
  pauseGame();
});

function pauseGame() {
  // Logic to pause game state.
}
Parameters
callback: (() => void) the callback function to be triggered.
Returns
(() => void) a function to unset the callback that is usually unused.

onResume

onResume(callback: (() => void)): (() => void)
Sets a callback to be triggered when a resume game event is fired from YouTube.

After being paused, the game is not guaranteed to resume.
Example
ytgame.system.onResume(() => {
  resumeGame();
});

function resumeGame() {
  // Logic to resume game state.
}
Parameters
callback: (() => void) the callback function to be triggered.
Returns
(() => void) a function to unset the callback that is usually unused.