Socket
Socket
Sign inDemoInstall

youtube-player-plus

Package Overview
Dependencies
1
Maintainers
1
Versions
7
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    youtube-player-plus

Enhanced wrapper for the Youtube Iframe API


Version published
Weekly downloads
12
increased by140%
Maintainers
1
Install size
114 kB
Created
Weekly downloads
 

Readme

Source

Youtube Player Plus ✨

Youtube Player Plus is an easy-to-use and customizable library for embedding video playback from Youtube in your web application.

Inspired by this package: yt-player

MIT License NPM version Downloads image

Features

  • 🌐 Utilizes the YouTube IFrame Player API
  • ⚡️ Offers an incredibly fast initial loading time
    • Automatically loads the YouTube IFrame API <script> during first use
    • For an even quicker start, include <script src='https://www.youtube.com/iframe_api' defer></script> in your webpage
    • Ensures API <script> isn't loaded twice by detecting its presence
  • 🚀 API commands are smoothly queued up (wait until both IFrame API and Player instance are ready)
  • ⚠️  Distinguishes between serious errors and unplayable video issues
  • ⏲️ Incorporates the crucial 'timeupdate' event that YouTube API is missing
  • 💡 Clear and detailed code comments for easy comprehension
  • 💯 Strongly typed.
  • 📦 Does not rely on large dependencies or unnecessary code

Installation

Use the package manager npm to install youtube-player-plus.

 npm i youtube-player-plus

Usage

Quick Start

1.  Install and import YouTubePlayerPlus:

import YouTubePlayerPlus from 'youtube-player-plus';

2.  Create an instance with an element reference and an optional config object:

const element = 'your-element-selector'; // Or an HTMLElement reference
const options = {}; // Optional configuration object
const player = new YouTubePlayerPlus(element, options);

3.  Load a video and control playback:

player.load(videoId, autoplay, start);
player.play();
player.pause();
player.stop();

4.  Listen to events:

import type { YTAPI_PlaybackQuality, YTAPI_PlaybackRate } from 'youtube-player-plus/types'

player.on('playing', () => {});

player.on('timeupdate', (current_time: number) => {
    console.log('Current time:', current_time);
})

player.on('playbackQualityChange', (quality: YTAPI_PlaybackQuality) => {
    console.log('Player quality changed to', quality)
})

player.on('playbackRateChange', (rate: YTAPI_PlaybackRate) => {
    console.log('Player rate changed to', rate)
})

Constructor

YouTubePlayerPlus(element: HTMLElement | string, options?: YT_IFRAME_OPTIONS)

Parameters

element : HTMLElement or CSS selector - Target element or CSS selector where the YouTube player will be initialized.

options : Object - Optional configuration object for the YouTube player, default values specified below:

PropertyTypeDefaultValueDescription
widthnumber640The width of the player
heightnumber360The height of the player
autoplaybooleanfalseDetermines if the video should autoplay when loaded
captionsstringundefinedSets the default language for captions
controlsbooleantrueIndicates whether the video player controls are displayed
keyboardbooleantrueEnables/disables keyboard controls
fullscreenbooleantrueDetermines if the fullscreen button is displayed in the player
annotationsbooleantrueDisplays video annotations by default
modestBrandingbooleanfalseHides the YouTube logo in the control bar
relatedVideosbooleantrueShows related videos from the same channel (0) or any channel (1) when playback ends
timeUpdateFrequencynumber0Determines the frequency (in ms) of 'timeupdate' events being emitted
playsInlinebooleantrueControls whether videos play inline or fullscreen on iOS
startnumber0Sets the start time of the video in seconds
debugbooleanfalseEnables debug mode which logs additional messages to console
hoststring'https://www.youtube-nocookie.com'Determines the hostname where videos are loaded from

Methods

MethodDescription
load(videoId: string, autoplay?: boolean, start?: number)Load the YouTube video.
play()Play the loaded video.
pause()Pause the loaded video.
stop()Stop the loaded video.
seek(seconds: number)Set the current playback time in seconds.
setVolume(volume: number)Sets the player volume.
getVolume(): numberGets the current player volume.
mute()Mutes the player.
unMute()Unmutes the player.
isMuted(): booleanGet the current mute state of the player.
setSize(width: number, height: number)Set the player's size, using the provided width and height values.
getSize(): {width: number, height: number}Get the current player size.
setPlaybackRate(rate: number)Sets the playback rate.
getPlaybackRate(): numberGets the current playback rate.
getAvailablePlaybackRates(): number[]Get a list of available playback rates.
setPlaybackQuality(suggestedQuality: YT_PLAYBACK_QUALITIES)Sets the suggested playback quality.
getPlaybackQuality(): stringGets the current playback quality.
getAvailablePlaybackQualities(): string[]Get a list of available playback qualities.
getDuration(): numberGets the total video duration in seconds.
getProgress(): numberGets the loaded video fraction, ranging from 0 to 1.
getState(): stringGets the current player state.
getYouTubeInstance(): objectGets the currently used YouTube Player API instance, if available.
getPercentageWatched(): numberGets the percentage of the video watched relative to the total duration, 0 to 1.
getCurrentTime(): numberIt returns the current time of the video in seconds.
destroy()Destroys the player instance and removes event listeners.

Getters/Setters

PropertyGetterSetterDescription
currentTimeGet or set the current playback time in seconds.
volumeGet or set the player volume.
mutedGet or set the mute state of the player.
sizeGet or set the player size with a given width and height; retrieves the current size.
playbackRateGet or set the playback rate.
playbackQualityGet or set the current/suggested playback quality.
availablePlaybackQualities Get a list of available playback qualities.
availablePlaybackRates Get a list of available playback rates.
duration Gets the total video duration in seconds.
progress Gets the loaded video fraction, ranging from 0 to 1.
state Gets the current player state.
youTubeInstance Gets the currently used YouTube Player API instance, if available.
percentageWatched Gets the percentage of the video watched relative to the total duration, 0 to 1.

Events

EventData
errorerror: Error
unplayablevideoId: string
timeupdatecurrentTime: number
unstarted 
ended 
playing 
cued 
playbackQualityChangequality: YTAPI_PlaybackQuality
playbackRateChangerate: YTAPI_PlaybackRate
stateChange 
ready 
buffering 

Listen to events

To listen to an event:

player.on('event-name', (eventData) => {
  // Your event handling logic here
});

To stop listening to an event:

player.removeListener('event-name', eventHandlerFunction);

Examples:

Contributing

Pull requests are welcome. For major changes, please open an issue first
to discuss what you would like to change.

Please make sure to update tests as appropriate.

License

MIT

Keywords

FAQs

Last updated on 07 Dec 2023

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc