AI-generated Key Takeaways
-
The YouTube Playables SDK is a web SDK that enables HTML5 games to integrate with the YouTube environment, providing a robust API for various gaming functionalities.
-
To use the SDK, games must include an
index.html
file and import the SDK via a specific script tag, ensuring the SDK is loaded before any game code, with a test suite available for integration verification. -
Games must call
firstFrameReady()
and thengameReady()
to signal that the game is ready to be displayed and interacted with, respectively, which are critical steps for the game to function on YouTube. -
The SDK offers APIs for player engagement, allowing games to send scores via
sendScore()
and open YouTube videos usingopenYTContent()
, enhancing the player experience. -
The SDK provides functions to manage game data, such as
loadData()
andsaveData()
, and to handle game health and system interactions, including logging errors/warnings and managing audio/pause/resume states.
ytgame
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 | |
---|---|
Sdk
|
The types of errors that the YouTube Playables SDK throws. |
Classes | |
---|---|
Sdk
|
The error object that the YouTube Playables SDK throws. |
Variables | |
---|---|
IN_
|
Whether or not the game is running within the Playables environment. |
SDK_
|
The YouTube Playables SDK version. |
Enumerations
Const
SdkErrorType
SdkErrorType
Variables
Const
IN_PLAYABLES_ENV
IN_PLAYABLES_ENV: boolean
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
- Example
-
// Prints the SDK version to console. Do not do this in production. console.log(ytgame.SDK_VERSION);
ytgame.SdkError
Error
The
SdkError
object is a child of
Error
and contains an additional field.
Constructors | |
---|---|
constructor
|
Properties | |
---|---|
error
|
The type of the error. |
message
|
|
name
|
|
stack
|
Properties
errorType
errorType:
SdkErrorType
ytgame.ads
The functions and properties related to ads.
Functions | |
---|---|
request
|
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
Interfaces | |
---|---|
Content
|
The content object the game sends to YouTube. |
Score
|
The score object the game sends to YouTube. |
Functions | |
---|---|
open
|
Requests YouTube to open content corresponding to the provided video ID.
|
send
|
Sends a score to YouTube. |
Functions
openYTContent
openYTContent(content: Content): Promise<void>
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>
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
Properties | |
---|---|
id
|
The ID of the video we want to open. |
Properties
id
id: string
ytgame.engagement.Score
Properties | |
---|---|
value
|
The score value expressed as an integer. |
Properties
value
value: number
ytgame.game
Functions | |
---|---|
first
|
Notifies YouTube that the game has begun showing frames. |
game
|
Notifies YouTube that the game is ready for players to interact with.
|
load
|
Loads game data from YouTube in the form of a serialized string. |
save
|
Saves game data to the YouTube in the form of a serialized string. |
Functions
firstFrameReady
firstFrameReady(): void
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
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>
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>
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
Functions | |
---|---|
log
|
Logs an error to YouTube. |
log
|
Logs a warning to YouTube. |
Functions
logError
logError(): void
Note: This API is best-effort and rate-limited which can result in data loss.
- Example
-
function onError() { ytgame.health.logError(); }
logWarning
logWarning(): void
Note: This API is best-effort and rate-limited which can result in data loss.
- Example
-
function onWarning() { ytgame.health.logWarning(); }
ytgame.system
Functions | |
---|---|
get
|
Returns the language that is set in the user's YouTube settings in the form of
a BCP-47 language tag.
|
is
|
Returns whether the game audio is enabled in the YouTube settings. |
on
|
Sets a callback to be triggered when the audio settings change event is fired from
YouTube.
|
on
|
Sets a callback to be triggered when a pause game event is fired from YouTube.
|
on
|
Sets a callback to be triggered when a resume game event is fired from YouTube.
|
Functions
getLanguage
getLanguage(): Promise<string>
Do not use other functions to determine the user's language or locale, or store their language preference in the cloud save. Instead, use this function to ensure that the user experience is consistent across YouTube.
- 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
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)
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)
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)
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. |