Skip to content

Cap-go/capacitor-youtube-player

@capgo/capacitor-youtube-player

Capgo - Instant updates for capacitor

Embed YouTube player controls in Capacitor apps

Documentation

The most complete doc is available here: https://capgo.app/docs/plugins/youtube-player/

Install

npm install @capgo/capacitor-youtube-player
npx cap sync

Native Implementation

iOS

This plugin uses native WKWebView for iOS playback, which provides:

  • Fullscreen-only playback mode for immersive viewing experience
  • Direct YouTube iframe API integration
  • Support for all YouTube iframe API parameters
  • Native iOS modal presentation
  • Cookie support for authentication via WKWebView's HTTPCookieStore
  • No external dependencies - pure iOS SDK

Important: iOS always plays videos in fullscreen mode for the best user experience.

Android

This plugin uses android-youtube-player for native Android playback, which provides:

  • Modern, actively maintained library
  • Fullscreen support with immersive mode
  • Direct YouTube iframe API integration
  • Lifecycle-aware components
  • Cookie support via CookieManager
  • No API key required

Note: Uses YouTube's iframe API internally, providing a consistent experience across platforms.

Privacy & GDPR Compliance

This plugin now supports privacy-enhanced mode for better GDPR compliance. When enabled, the plugin uses youtube-nocookie.com domain instead of youtube.com, which prevents YouTube from storing visitor information until they actually play the video.

Usage with Privacy-Enhanced Mode

import { YoutubePlayer } from '@capgo/capacitor-youtube-player';

await YoutubePlayer.initialize({
  playerId: 'my-player',
  videoId: 'dQw4w9WgXcQ',
  playerSize: { width: 640, height: 360 },
  privacyEnhanced: true  // Enable privacy-enhanced mode
});

Important Platform Notes:

  • Web: The privacyEnhanced option uses youtube-nocookie.com domain for better privacy
  • iOS: Uses native WKWebView for fullscreen-only playback with YouTube iframe API
  • Android: Uses android-youtube-player library with YouTube iframe API

For full GDPR compliance, you should also:

  • Display a cookie consent banner before loading videos
  • Update your privacy policy to disclose YouTube's data collection
  • Consider implementing a "click to load" placeholder for videos

Cookie Support (Preventing Bot Detection)

The plugin now supports passing cookies to the YouTube player to help prevent the "sign in to confirm you're not a bot" message that YouTube sometimes displays.

Usage with Cookies

import { YoutubePlayer } from '@capgo/capacitor-youtube-player';

await YoutubePlayer.initialize({
  playerId: 'my-player',
  videoId: 'dQw4w9WgXcQ',
  playerSize: { width: 640, height: 360 },
  cookies: 'CONSENT=YES+cb; VISITOR_INFO1_LIVE=xyz123'  // Your YouTube cookies
});

Platform Support:

  • Web: âś… Cookies are set via document.cookie with SameSite=None; Secure attributes
  • iOS: âś… Cookies are set in WKWebView's HTTPCookieStore for the .youtube.com domain (native WKWebView, fullscreen-only mode)
  • Android: âś… Cookies are set via CookieManager in the WebView for YouTube domains

Important Notes:

  • Cookie Format: Pass cookies as a semicolon-separated string (e.g., "name1=value1; name2=value2")
  • Getting Cookies: You can obtain valid YouTube cookies from your browser's developer tools when signed into YouTube
  • Security: All cookies are automatically set with secure attributes (HTTPS only)
  • Domain: Cookies are set for .youtube.com to work across all YouTube subdomains
  • Android: Uses android-youtube-player library which is based on YouTube's iframe API, so cookies work similarly to the web platform

Common YouTube Cookies:

  • CONSENT: YouTube consent cookie (helps with GDPR compliance)
  • VISITOR_INFO1_LIVE: Visitor tracking cookie
  • YSC: YouTube session cookie
  • PREF: User preferences cookie

API

YouTube Player Plugin interface for Capacitor. Provides methods to control YouTube video playback in your app.

initialize(...)

initialize(options: IPlayerOptions) => Promise<{ playerReady: boolean; player: string; } | undefined>

Initialize a new YouTube player instance.

Param Type Description
options IPlayerOptions - Configuration options for the player

Returns: Promise<{ playerReady: boolean; player: string; }>


destroy(...)

destroy(playerId: string) => Promise<{ result: { method: string; value: boolean; }; }>

Destroy a player instance and free resources.

Param Type Description
playerId string - ID of the player to destroy

Returns: Promise<{ result: { method: string; value: boolean; }; }>


stopVideo(...)

stopVideo(playerId: string) => Promise<{ result: { method: string; value: boolean; }; }>

Stop video playback and cancel loading. Use this sparingly - pauseVideo() is usually preferred.

Param Type Description
playerId string - ID of the player

Returns: Promise<{ result: { method: string; value: boolean; }; }>


playVideo(...)

playVideo(playerId: string) => Promise<{ result: { method: string; value: boolean; }; }>

Play the currently cued or loaded video. Final player state will be PLAYING (1).

Param Type Description
playerId string - ID of the player

Returns: Promise<{ result: { method: string; value: boolean; }; }>


pauseVideo(...)

pauseVideo(playerId: string) => Promise<{ result: { method: string; value: boolean; }; }>

Pause the currently playing video. Final player state will be PAUSED (2), unless already ENDED (0).

Param Type Description
playerId string - ID of the player

Returns: Promise<{ result: { method: string; value: boolean; }; }>


seekTo(...)

seekTo(playerId: string, seconds: number, allowSeekAhead: boolean) => Promise<{ result: { method: string; value: boolean; seconds: number; allowSeekAhead: boolean; }; }>

Seek to a specific time in the video. If player is paused, it remains paused. If playing, continues playing.

Param Type Description
playerId string - ID of the player
seconds number - Time to seek to (in seconds)
allowSeekAhead boolean - Whether to make a new request to server if not buffered

Returns: Promise<{ result: { method: string; value: boolean; seconds: number; allowSeekAhead: boolean; }; }>


loadVideoById(...)

loadVideoById(playerId: string, options: IVideoOptionsById) => Promise<{ result: { method: string; value: boolean; options: IVideoOptionsById; }; }>

Load and play a video by its YouTube ID.

Param Type Description
playerId string - ID of the player
options IVideoOptionsById - Video loading options (ID, start time, quality, etc.)

Returns: Promise<{ result: { method: string; value: boolean; options: IVideoOptionsById; }; }>


cueVideoById(...)

cueVideoById(playerId: string, options: IVideoOptionsById) => Promise<{ result: { method: string; value: boolean; options: IVideoOptionsById; }; }>

Cue a video by ID without playing it. Loads thumbnail and prepares player, but doesn't request video until playVideo() called.

Param Type Description
playerId string - ID of the player
options IVideoOptionsById - Video cuing options (ID, start time, quality, etc.)

Returns: Promise<{ result: { method: string; value: boolean; options: IVideoOptionsById; }; }>


loadVideoByUrl(...)

loadVideoByUrl(playerId: string, options: IVideoOptionsByUrl) => Promise<{ result: { method: string; value: boolean; options: IVideoOptionsByUrl; }; }>

Load and play a video by its full URL.

Param Type Description
playerId string - ID of the player
options IVideoOptionsByUrl - Video loading options including media URL

Returns: Promise<{ result: { method: string; value: boolean; options: IVideoOptionsByUrl; }; }>


cueVideoByUrl(...)

cueVideoByUrl(playerId: string, options: IVideoOptionsByUrl) => Promise<{ result: { method: string; value: boolean; options: IVideoOptionsByUrl; }; }>

Cue a video by URL without playing it.

Param Type Description
playerId string - ID of the player
options IVideoOptionsByUrl - Video cuing options including media URL

Returns: Promise<{ result: { method: string; value: boolean; options: IVideoOptionsByUrl; }; }>


cuePlaylist(...)

cuePlaylist(playerId: string, playlistOptions: IPlaylistOptions) => Promise<{ result: { method: string; value: boolean; }; }>

Cue a playlist without playing it. Loads playlist and prepares first video.

Param Type Description
playerId string - ID of the player
playlistOptions IPlaylistOptions - Playlist configuration (type, ID, index, etc.)

Returns: Promise<{ result: { method: string; value: boolean; }; }>


loadPlaylist(...)

loadPlaylist(playerId: string, playlistOptions: IPlaylistOptions) => Promise<{ result: { method: string; value: boolean; }; }>

Load and play a playlist.

Param Type Description
playerId string - ID of the player
playlistOptions IPlaylistOptions - Playlist configuration (type, ID, index, etc.)

Returns: Promise<{ result: { method: string; value: boolean; }; }>


nextVideo(...)

nextVideo(playerId: string) => Promise<{ result: { method: string; value: boolean; }; }>

Play the next video in the playlist.

Param Type Description
playerId string - ID of the player

Returns: Promise<{ result: { method: string; value: boolean; }; }>


previousVideo(...)

previousVideo(playerId: string) => Promise<{ result: { method: string; value: boolean; }; }>

Play the previous video in the playlist.

Param Type Description
playerId string - ID of the player

Returns: Promise<{ result: { method: string; value: boolean; }; }>


playVideoAt(...)

playVideoAt(playerId: string, index: number) => Promise<{ result: { method: string; value: boolean; }; }>

Play a specific video in the playlist by index.

Param Type Description
playerId string - ID of the player
index number - Zero-based index of the video to play

Returns: Promise<{ result: { method: string; value: boolean; }; }>


mute(...)

mute(playerId: string) => Promise<{ result: { method: string; value: boolean; }; }>

Mute the player audio.

Param Type Description
playerId string - ID of the player

Returns: Promise<{ result: { method: string; value: boolean; }; }>


unMute(...)

unMute(playerId: string) => Promise<{ result: { method: string; value: boolean; }; }>

Unmute the player audio.

Param Type Description
playerId string - ID of the player

Returns: Promise<{ result: { method: string; value: boolean; }; }>


isMuted(...)

isMuted(playerId: string) => Promise<{ result: { method: string; value: boolean; }; }>

Check if the player is currently muted.

Param Type Description
playerId string - ID of the player

Returns: Promise<{ result: { method: string; value: boolean; }; }>


setVolume(...)

setVolume(playerId: string, volume: number) => Promise<{ result: { method: string; value: number; }; }>

Set the player volume level.

Param Type Description
playerId string - ID of the player
volume number - Volume level from 0 (silent) to 100 (max)

Returns: Promise<{ result: { method: string; value: number; }; }>


getVolume(...)

getVolume(playerId: string) => Promise<{ result: { method: string; value: number; }; }>

Get the current player volume level. Returns volume even if player is muted.

Param Type Description
playerId string - ID of the player

Returns: Promise<{ result: { method: string; value: number; }; }>


setSize(...)

setSize(playerId: string, width: number, height: number) => Promise<{ result: { method: string; value: { width: number; height: number; }; }; }>

Set the player dimensions in pixels.

Param Type Description
playerId string - ID of the player
width number - Width in pixels
height number - Height in pixels

Returns: Promise<{ result: { method: string; value: { width: number; height: number; }; }; }>


getPlaybackRate(...)

getPlaybackRate(playerId: string) => Promise<{ result: { method: string; value: number; }; }>

Get the current playback rate.

Param Type Description
playerId string - ID of the player

Returns: Promise<{ result: { method: string; value: number; }; }>


setPlaybackRate(...)

setPlaybackRate(playerId: string, suggestedRate: number) => Promise<{ result: { method: string; value: boolean; }; }>

Set the playback speed.

Param Type Description
playerId string - ID of the player
suggestedRate number - Desired playback rate (0.25 to 2.0)

Returns: Promise<{ result: { method: string; value: boolean; }; }>


getAvailablePlaybackRates(...)

getAvailablePlaybackRates(playerId: string) => Promise<{ result: { method: string; value: number[]; }; }>

Get list of available playback rates for current video.

Param Type Description
playerId string - ID of the player

Returns: Promise<{ result: { method: string; value: number[]; }; }>


setLoop(...)

setLoop(playerId: string, loopPlaylists: boolean) => Promise<{ result: { method: string; value: boolean; }; }>

Enable or disable playlist looping. When enabled, playlist will restart from beginning after last video.

Param Type Description
playerId string - ID of the player
loopPlaylists boolean - true to loop, false to stop after last video

Returns: Promise<{ result: { method: string; value: boolean; }; }>


setShuffle(...)

setShuffle(playerId: string, shufflePlaylist: boolean) => Promise<{ result: { method: string; value: boolean; }; }>

Enable or disable playlist shuffle.

Param Type Description
playerId string - ID of the player
shufflePlaylist boolean - true to shuffle, false for sequential

Returns: Promise<{ result: { method: string; value: boolean; }; }>


getVideoLoadedFraction(...)

getVideoLoadedFraction(playerId: string) => Promise<{ result: { method: string; value: number; }; }>

Get the fraction of the video that has been buffered. More reliable than deprecated getVideoBytesLoaded/getVideoBytesTotal.

Param Type Description
playerId string - ID of the player

Returns: Promise<{ result: { method: string; value: number; }; }>


getPlayerState(...)

getPlayerState(playerId: string) => Promise<{ result: { method: string; value: number; }; }>

Get the current state of the player.

Param Type Description
playerId string - ID of the player

Returns: Promise<{ result: { method: string; value: number; }; }>


getAllPlayersEventsState()

getAllPlayersEventsState() => Promise<{ result: { method: string; value: Map<string, IPlayerState>; }; }>

Get event states for all active players. Useful for tracking multiple player instances.

Returns: Promise<{ result: { method: string; value: Map<string, IPlayerState>; }; }>


getCurrentTime(...)

getCurrentTime(playerId: string) => Promise<{ result: { method: string; value: number; }; }>

Get the current playback position in seconds.

Param Type Description
playerId string - ID of the player

Returns: Promise<{ result: { method: string; value: number; }; }>


toggleFullScreen(...)

toggleFullScreen(playerId: string, isFullScreen: boolean | null | undefined) => Promise<{ result: { method: string; value: boolean | null | undefined; }; }>

Toggle fullscreen mode on or off.

Param Type Description
playerId string - ID of the player
isFullScreen boolean | null - true for fullscreen, false for normal, null/undefined to toggle

Returns: Promise<{ result: { method: string; value: boolean | null; }; }>


getPlaybackQuality(...)

getPlaybackQuality(playerId: string) => Promise<{ result: { method: string; value: IPlaybackQuality; }; }>

Get the current playback quality.

Param Type Description
playerId string - ID of the player

Returns: Promise<{ result: { method: string; value: IPlaybackQuality; }; }>


setPlaybackQuality(...)

setPlaybackQuality(playerId: string, suggestedQuality: IPlaybackQuality) => Promise<{ result: { method: string; value: boolean; }; }>

Set the suggested playback quality. Actual quality may differ based on network conditions.

Param Type Description
playerId string - ID of the player
suggestedQuality IPlaybackQuality - Desired quality level

Returns: Promise<{ result: { method: string; value: boolean; }; }>


getAvailableQualityLevels(...)

getAvailableQualityLevels(playerId: string) => Promise<{ result: { method: string; value: IPlaybackQuality[]; }; }>

Get list of available quality levels for current video.

Param Type Description
playerId string - ID of the player

Returns: Promise<{ result: { method: string; value: IPlaybackQuality[]; }; }>


getDuration(...)

getDuration(playerId: string) => Promise<{ result: { method: string; value: number; }; }>

Get the duration of the current video in seconds.

Param Type Description
playerId string - ID of the player

Returns: Promise<{ result: { method: string; value: number; }; }>


getVideoUrl(...)

getVideoUrl(playerId: string) => Promise<{ result: { method: string; value: string; }; }>

Get the YouTube.com URL for the current video.

Param Type Description
playerId string - ID of the player

Returns: Promise<{ result: { method: string; value: string; }; }>


getVideoEmbedCode(...)

getVideoEmbedCode(playerId: string) => Promise<{ result: { method: string; value: string; }; }>

Get the embed code for the current video. Returns HTML iframe embed code.

Param Type Description
playerId string - ID of the player

Returns: Promise<{ result: { method: string; value: string; }; }>


getPlaylist(...)

getPlaylist(playerId: string) => Promise<{ result: { method: string; value: string[]; }; }>

Get array of video IDs in the current playlist.

Param Type Description
playerId string - ID of the player

Returns: Promise<{ result: { method: string; value: string[]; }; }>


getPlaylistIndex(...)

getPlaylistIndex(playerId: string) => Promise<{ result: { method: string; value: number; }; }>

Get the index of the currently playing video in the playlist.

Param Type Description
playerId string - ID of the player

Returns: Promise<{ result: { method: string; value: number; }; }>


getIframe(...)

getIframe(playerId: string) => Promise<{ result: { method: string; value: HTMLIFrameElement; }; }>

Get the iframe DOM element for the player. Web platform only.

Param Type Description
playerId string - ID of the player

Returns: Promise<{ result: { method: string; value: any; }; }>


addEventListener(...)

addEventListener<TEvent extends PlayerEvent>(playerId: string, eventName: keyof Events, listener: (event: TEvent) => void) => void

Add an event listener to the player.

Param Type Description
playerId string - ID of the player
eventName keyof Events - Name of the event (onReady, onStateChange, onError, etc.)
listener (event: TEvent) => void - Callback function to handle the event

removeEventListener(...)

removeEventListener<TEvent extends PlayerEvent>(playerId: string, eventName: keyof Events, listener: (event: TEvent) => void) => void

Remove an event listener from the player.

Param Type Description
playerId string - ID of the player
eventName keyof Events - Name of the event to remove listener from
listener (event: TEvent) => void - The callback function to remove

getPluginVersion()

getPluginVersion() => Promise<{ version: string; }>

Get the plugin version number. Returns platform-specific version information.

Returns: Promise<{ version: string; }>


Interfaces

IPlayerOptions

Configuration options for initializing a YouTube player instance. All size and playback settings are configured through this interface.

Prop Type Description Default
playerId string Unique identifier for the player instance. Used to reference this player in API calls.
playerSize IPlayerSize Dimensions of the player in pixels.
videoId string YouTube video ID to load.
fullscreen boolean Whether to start the video in fullscreen mode. false
playerVars IPlayerVars YouTube player parameters to customize playback behavior. See: https://developers.google.com/youtube/player_parameters
debug boolean Enable debug logging for troubleshooting. false
privacyEnhanced boolean Use privacy-enhanced mode (youtube-nocookie.com) for better GDPR compliance. When enabled, YouTube won't store information about visitors on your website unless they play the video. Note: Only applies to web platform. Native platforms use different APIs. false
cookies string Cookies to be set for the YouTube player. This can help bypass the "sign in to confirm you're not a bot" message. Pass cookies as a semicolon-separated string (e.g., "name1=value1; name2=value2"). Platform Support: - Web: Sets cookies via document.cookie - iOS: Sets cookies in WKWebView's HTTPCookieStore - Android: Sets cookies via CookieManager (note: native YouTube Player API has separate session management) undefined

IPlayerSize

Player dimensions in pixels.

Prop Type Description
height number Height in pixels
width number Width in pixels

IPlayerVars

YouTube player parameters for customizing player behavior and appearance.

Prop Type Description
autoplay number Whether to autoplay the video (0 = no, 1 = yes)
cc_load_policy number Force closed captions to show by default (1 = show)
color string Player controls color ('red' or 'white')
controls number Whether to show player controls (0 = hide, 1 = show, 2 = show on load)
disablekb number Disable keyboard controls (0 = enable, 1 = disable)
enablejsapi number Enable JavaScript API (1 = enable)
end number Time in seconds to stop playback
fs number Show fullscreen button (0 = hide, 1 = show)
hl string Player interface language (ISO 639-1 code)
iv_load_policy number Show video annotations (1 = show, 3 = hide)
list string Playlist or content ID to load
listType string Type of content in 'list' parameter
loop number Loop the video (0 = no, 1 = yes, requires playlist)
modestbranding number Hide YouTube logo (0 = show, 1 = hide)
origin string Domain origin for extra security
playlist string Comma-separated list of video IDs to play
playsinline number Play inline on iOS (0 = fullscreen, 1 = inline)
rel number Show related videos (0 = from same channel, 1 = any)
showinfo number Show video information (deprecated, always hidden)
start number Time in seconds to start playback

IVideoOptionsById

Options for loading a video by its YouTube ID.

Prop Type Description
videoId string YouTube video ID

IVideoOptionsByUrl

Options for loading a video by its media URL.

Prop Type Description
mediaContentUrl string Full YouTube video URL

IPlaylistOptions

Options for loading and playing YouTube playlists.

Prop Type Description
listType 'playlist' | 'search' | 'user_uploads' Type of playlist to load
list string Playlist ID or search query (depending on listType)
playlist string[] Array of video IDs to play as a playlist
index number Index of the video to start with (0-based)
startSeconds number Time in seconds to start the first video
suggestedQuality string Suggested playback quality

Map

Prop Type
size number
Method Signature
clear () => void
delete (key: K) => boolean
forEach (callbackfn: (value: V, key: K, map: Map<K, V>) => void, thisArg?: any) => void
get (key: K) => V | undefined
has (key: K) => boolean
set (key: K, value: V) => this

IPlayerState

Internal state tracking for player events. Used to monitor which events have been triggered.

Prop Type Description
events { onReady?: unknown; onStateChange?: unknown; onPlaybackQualityChange?: unknown; onError?: unknown; } Event handlers and their states

PlayerEvent

Base interface for events triggered by a player.

Prop Type Description
target Element Video player corresponding to the event.

Events

  • Handlers for events fired by the player.
Prop Type Description
onReady PlayerEventHandler<PlayerEvent> Event fired when a player has finished loading and is ready to begin receiving API calls.
onStateChange PlayerEventHandler<OnStateChangeEvent> Event fired when the player's state changes.
onPlaybackQualityChange PlayerEventHandler<OnPlaybackQualityChangeEvent> Event fired when the playback quality of the player changes.
onPlaybackRateChange PlayerEventHandler<OnPlaybackRateChangeEvent> Event fired when the playback rate of the player changes.
onError PlayerEventHandler<OnErrorEvent> Event fired when an error in the player occurs
onApiChange PlayerEventHandler<PlayerEvent> Event fired to indicate that the player has loaded, or unloaded, a module with exposed API methods. This currently only occurs for closed captioning.

PlayerEventHandler

Handles a player event.

OnStateChangeEvent

Event for player state change.

Prop Type Description
data PlayerState New player state.

OnPlaybackQualityChangeEvent

Event for playback quality change.

Prop Type Description
data string New playback quality.

OnPlaybackRateChangeEvent

Event for playback rate change.

Prop Type Description
data number New playback rate.

OnErrorEvent

Event for a player error.

Prop Type Description
data PlayerError Which type of error occurred.

Enums

IPlaybackQuality

Members Value Description
SMALL 'small' Small quality (240p)
MEDIUM 'medium' Medium quality (360p)
LARGE 'large' Large quality (480p)
HD720 'hd720' High definition 720p
HD1080 'hd1080' High definition 1080p
HIGH_RES 'highres' Highest resolution available (1440p+)
DEFAULT 'default' Default quality selected by YouTube

PlayerState

Members Value Description
UNSTARTED -1 Video has not started (-1)
ENDED 0 Video has ended (0)
PLAYING 1 Video is currently playing (1)
PAUSED 2 Video is paused (2)
BUFFERING 3 Video is buffering (3)
CUED 5 Video is cued and ready to play (5)

PlayerError

Members Value Description
InvalidParam 2 The request contained an invalid parameter value.
Html5Error 5 The requested content cannot be played in an HTML5 player.
VideoNotFound 100 The video requested was not found.
EmbeddingNotAllowed 101 The owner of the requested video does not allow it to be played in embedded players.
EmbeddingNotAllowed2 150 This error is the same as 101. It's just a 101 error in disguise!

About

Capacitor plugin player to embed YouTube player controls in Capacitor apps

Topics

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Sponsor this project

  •  

Packages

No packages published

Contributors 5