YouTube Playables SDK is a web SDK for connecting HTML5 games with the YouTube environment. The SDK features a robust API to support games in a variety of ways to create an excellent gaming experience on YouTube.
Get started
A game should have an index.html
file in the root directory. Import the
YouTube Playables SDK by adding this line before any of your game code:
<script src="https://www.youtube.com/game_api/v1"></script>
Note: The SDK MUST be loaded before any of your game code.
The SDK would be no-op when your game is served locally. To verify SDK integration correctness, use the test suite guide.
TypeScript type definitions
For games using TypeScript, download type definitions.
Samples games
Sample are available that demonstrate how to integrate with YouTube Playables SDK, including plain JavaScript, Flutter web, and Unity.
ytgame
The top level namespace for the YouTube Playables SDK.
SDK_VERSION
The YouTube Playables SDK version.
SDK_VERSION: string;
Example:
// Print SDK version. Example: "1.0.12345".
console.log(ytgame.SDK_VERSION);
IN_PLAYABLES_ENV
Whether or not the game is running as a playable.
IN_PLAYABLES_ENV: boolean;
Example:
// An example of where one may want to fork behavior.
if (ytgame?.IN_PLAYABLES_ENV) {
ytgame.game.saveData(dataStr);
} else {
window.localStorage.setItem('SAVE_DATA', dataStr);
}
SdkErrorType
The types of errors that the YouTube Playables SDK throws. The list of error types are as follows:
UNKNOWN
: The error is unknown.API_UNAVAILABLE
: The API is temporarily unavailable. Ask players to retry at a later time if they're in a critical flow.INVALID_PARAMS
: The API is called with invalid parameters.SIZE_LIMIT_EXCEEDED
: The API is called with parameters exceeding the size limit.
enum SdkErrorType {
UNKNOWN,
API_UNAVAILABLE,
INVALID_PARAMS,
SIZE_LIMIT_EXCEEDED,
}
SdkError
The error object that the YouTube Playables SDK throws.
The SdkError
object is a child of Error and contains an additional
field:
errorType
: The type of the error.
interface SdkError extends Error {
errorType: SdkErrorType;
}
Example:
try {
await ytgame.game.saveData();
} catch (e) {
if ((e as ytgame.SdkErrorType).errorType ==
ytgame.SdkErrorType.API_UNAVAILABLE) {
// Handle api unavailable error.
}
}
engagement
The functions and properties related to player engagement.
sendScore
An optional API that 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. Returns a Promise
that
completes when sending succeeds and rejects with an SdkError
when sending
fails.
The Score
object has the following field:
value:
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.
interface Score {
value: number; // score value expressed as an integer
}
sendScore(score: Score): Promise<void>
Example:
function onScoreAwarded(score: number) {
ytgame.engagement.sendScore({value: score});
}
game
The functions and properties related to the generic game behaviors.
firstFrameReady
Notifies YouTube that the game's first frame is ready to be shown.
firstFrameReady()
MUST be called before gameReady()
.
Note: The game MUST call this API. Otherwise, the game isn't shown on YouTube.
firstFrameReady(): void
Example:
function onGameInitialized() {
ytgame.game.firstFrameReady();
}
gameReady
Notifies YouTube that the game is ready for players to interact with.
firstFrameReady()
MUST be called before gameReady()
.
Note: The game MUST call this API when it is interactable. Otherwise, the game fails the YouTube certification process. For example, this API MUST NOT be called when a loading screen is shown.
gameReady(): void
Example:
function onGameInteractable() {
ytgame.game.gameReady();
}
loadData
Loads game data from the YouTube cloud in the form of a serialized string.
Returns a Promise
that completes when loading succeeds and rejects with an
SdkError
when loading fails.
This API is usually called before the game loads to resume the game state.
Note: Signed-out players are not supported. The Promise
completes with an
empty string.
loadData(): Promise<string>
Example:
ytgame.game.loadData().then((data) => {
// Process data to resume game state.
});
saveData
Saves game data to the YouTube cloud in the form of a serialized string. Returns
a Promise
that completes when saving succeeded and rejects with an SdkError
when failed. data
must be a valid, well-formed UTF-16 string without lone
surrogates.
It is recommended to save your data immediately after important milestones.
Note: Signed-out players are not supported. The Promise
completes but data
is not saved.
saveData(data: string): Promise<void>
Example:
ytgame.game.saveData(data).then(() => {
// Handle data save success.
}, (e) => {
// Handle data save failure.
});
health
The functions and properties related to the game health.
logError
Logs an error to YouTube.
Note: This API is best-effort and rate-limited which can result in data loss.
logError(): void
Example:
try {
doCriticalAction();
} catch (e) {
ytgame.health.logError();
}
logWarning
Logs a warning to YouTube.
Note: This API is best-effort and rate-limited which can result in data loss.
logWarning(): void
Example:
function onWarning() {
ytgame.health.logWarning();
}
system
The functions and properties related to the YouTube system.
isAudioEnabled
Returns whether the game audio is enabled in the YouTube settings.
isAudioEnabled(): boolean
Example:
function initGameSound() {
if (ytgame.system.isAudioEnabled()) {
// Enable game audio.
} else {
// Disable game audio.
}
}
onAudioEnabledChange
Sets a callback to be triggered when the audio settings change event is fired from YouTube. Returns a function to unset the callback. The callback has the following parameter:
isAudioEnabled:
Whether the audio is enabled in the YouTube settings.
Note: The game MUST use this API to update the game audio state.
onAudioEnabledChange(callback: (isAudioEnabled: boolean) => void): () => void
Example:
ytgame.system.onAudioEnabledChange((isAudioEnabled) => {
if (isAudioEnabled) {
// Enable game audio.
} else {
// Disable game audio.
}
});
onPause
Sets a callback to be triggered when a pause game event is fired from YouTube. Returns a function to unset the callback.
Note: You have a short window to save any state before your game gets evicted.
onPause(callback: () => void): () => void
Example:
ytgame.system.onPause(() => {
pauseGame();
});
function pauseGame() {
// Logic to pause game state.
}
onResume
Sets a callback to be triggered when a resume game event is fired from YouTube. Returns a function to unset the callback.
onResume(callback: () => void): () => void
Example:
ytgame.system.onResume(() => {
resumeGame();
});
function resumeGame() {
// Logic to resume game state.
}
getLanguage
Returns the BCP-47 language tag for the user's language set in YouTube. Note that this may be different than the system or browser language settings but should always match the language used in YouTube.
getLanguage(): Promise<string>
Example:
const localeTag = await ytgame.system.getLanguage();