Socket
Socket
Sign inDemoInstall

capacitor-youtube-player

Package Overview
Dependencies
4
Maintainers
2
Versions
175
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    capacitor-youtube-player

Capacitor Youtube Player


Version published
Weekly downloads
49
decreased by-74.21%
Maintainers
2
Install size
3.72 MB
Created
Weekly downloads
 

Readme

Source

Built With Capacitor

CapacitorYoutubePlayer

Ask me anything Version Downloads License

If this project has been useful to you and you want to help me to keep contributing to the open source with projects, examples, plugins,... collaborate and buy me a coffee.

Buy Me A Coffee

Capacitor Youtube Player is a custom Native Capacitor plugin to show Youtube Player on Web, IOS and Android platforms.

Technologies

Capacitor

Capacitor is a cross-platform API and code execution layer that makes it easy to call Native SDKs from web code and to write custom Native plugins that your app might need. Additionally, Capacitor provides first-class Progressive Web App support so you can write one app and deploy it to the app stores, and the mobile web.

Capacitor is being designed by the Ionic Framework team as an eventual alternative to Cordova, though backwards compatibility with Cordova plugins is a priority and is actively being worked on. Capacitor can be used without Ionic Framework, but soon it'll become a core part of the Ionic developer experience.

Capacitor also comes with a Plugin API for building native plugins. On iOS, first-class Swift support is available, and much of the iOS Capacitor runtime is written in Swift. Plugins may also be written in Objective-C. On Android, support for writing plugins with Java and Kotlin is supported.

Plugin preview

Ionic App

App

Plugin log mode

When initializing a youtube player you can enable debug mode to display the logs in the console.

    async initializeYoutubePlayerPluginWeb() {
      const options = {playerId: 'youtube-player', playerSize: {width: 640, height: 360}, videoId: 'tDW2C6rcH6M', debug: true};
      const result = await YoutubePlayerWeb.initialize(options);
  }

Methods available

WEB

IMPORTANT NOTE


Autoplay

Currently most browsers do not support autoplay unless the video is loaded without sound.

This is the behaviour of the web plugin if you pass a value of 1 in the autoplay parameter of playerVars. The video will start playing but without sound.

  ...
  playerVars: {
      autoplay: 1,
      rel: 0,
      color: 'white',
      showinfo: 1,
    },
  ...

You can read more about the autoplay policy in different browsers by clicking on the following links:

Google Chrome

Firefox

Fullscreen

To display a video in full screen, user interaction is required... either by clicking on the play button, another button,...

You can read more about the fullscreen policy in different browsers by clicking on the following links:

Google Chrome


FunctionalityMethodsDescriptionExpectsReturns
Load player API & Create Player & Destroy Playerinitialize(options: {playerId: string, playerSize: IPlayerSize, playerVars?: IPlayerVars, videoId: string, debug?: boolean})Promise - Load player API & create player.JSON Objectdata
Load player API & Create Player & Destroy Player destroy(playerId: string)Promise - Destroy playerstringdata
Playback controls and player settingsstopVideo(playerId: string)Promise - Stops and cancels loading of the current video. This function should be reserved for rare situations when you know that the user will not be watching additional video in the player. If your intent is to pause the video, you should just call the pauseVideo function. If you want to change the video that the player is playing, you can call one of the queueing functions without calling stopVideo first.stringdata
Playback controls and player settingsplayVideo(playerId: string)Promise - Plays the currently cued/loaded video. The final player state after this function executes will be playing (1).stringdata
Playback controls and player settingspauseVideo(playerId: string)Promise - Pauses the currently playing video. The final player state after this function executes will be paused (2) unless the player is in the ended (0) state when the function is called, in which case the player state will not change.stringdata
Playback controls and player settingsseekTo(playerId: string, seconds: number, allowSeekAhead: boolean)Promise - Seeks to a specified time in the video. If the player is paused when the function is called, it will remain paused. If the function is called from another state (playing, video cued, etc.), the player will play the video.string, number, booleandata
Playback controls and player settingsloadVideoById(playerId: string, options: {videoId: string, startSeconds?: number, endSeconds?: number, suggestedQuality?: string})Promise - Loads and plays the specified video.string, JSON Objectdata
Playback controls and player settingscueVideoById(playerId: string, options: {videoId: string, startSeconds?: number, endSeconds?: number, suggestedQuality?: string})Promise - Loads the specified video's thumbnail and prepares the player to play the video. The player does not request the FLV until playVideo() or seekTo() is called.string, JSON Objectdata
Changing the player volumemute(playerId: string)Promise - Mutes the player.stringdata
Changing the player volumeunMute(playerId: string)Promise - Unmutes the player.stringdata
Changing the player volumeisMuted(playerId: string)Promise - Returns true if the player is muted, false if not.stringdata
Changing the player volumesetVolume(playerId: string, volume: Number)Promise - Sets the volume. Accepts an integer between 0 and 100.string, numberdata
Changing the player volumegetVolume(playerId: string)Promise - Returns the player's current volume, an integer between 0 and 100. Note that getVolume() will return the volume even if the player is muted.stringdata
Setting the player sizesetSize(playerId: string, width:Number, height:Number)Promise - Sets the size in pixels of the that contains the player. string, number, numberdata
Playback statusgetVideoLoadedFraction(playerId: string)Promise - Returns a number between 0 and 1 that specifies the percentage of the video that the player shows as buffered. This method returns a more reliable number than the now-deprecated getVideoBytesLoaded and getVideoBytesTotal methods.stringdata
Playback statusgetPlayerState(playerId: string)Promise - Returns the state of the player. Possible values are: -1 unstarted / 0 ended / 1 playing / 2 paused / 3 buffering / 5 video cuedstringdata
Playback statusgetAllPlayersEventsState()Promise - Returns the state of events of all players.Map<string, IPlayerState>
Playback statusgetCurrentTime(playerId: string)Promise - Returns the elapsed time in seconds since the video started playing.stringdata

ANDROID

FunctionalityMethodsDescriptionExpectsReturns
Load player API & Create Playerinitialize(options: {playerSize: IPlayerSize, videoId: string}): Promise<{playerReady: boolean}>;Promise - Load player API & create player.JSON Objectdata

IOS

FunctionalityMethodsDescriptionExpectsReturns
Load player API & Create Playerinitialize(options: {playerSize: IPlayerSize, videoId: string}): Promise<{playerReady: boolean}>;Promise - Load player API & create player.JSON Objectdata

Install Plugin

    npm install --save capacitor-youtube-player@latest

Using this plugin

IMPORTANT NOTES ANDROID

-> If you get this error in ANDROID STUDIO

Error

To use the CAPACITOR YOUTUBE PLAYER plugin you need to add the YOUTUBE API KEY in the file local.properties.

YOUTUBE_API_KEY="YOUR_YOUTUBE_API_KEY"

If you don't have a local.properties file, create one. By default, this file is in the .gitignore. If not add it so that your keys are not visible to anyone.

In the official Capacitor documentation you have the instructions to migrate to version 3.0.

-> If you get this error in ANDROID STUDIO and your device uses Android 11 (API 30)

Error

Add the following to manifest tag in AndroidManifest to fix it:

<queries>
   <intent>
     <action android:name="com.google.android.youtube.api.service.START" />
   </intent>
</queries>

IMPORTANT NOTE ANDROID (CAPACITOR 2.0)


public class MainActivity extends BridgeActivity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Initializes the Bridge
    this.init(savedInstanceState, new ArrayList<Class<? extends Plugin>>() {{
      // Additional plugins you've installed go here
      // Ex: add(TotallyAwesomePlugin.class);
      add(YoutubePlayer.class); <= ADD THIS LINE
    }});
  }
}

In the official Capacitor documentation appears how to register the plugin.

IMPORTANT NOTE iOS (CAPACITOR 2.0)

Currently there is a small error when you testing the plugin in iOS. The following line of code needs to be modified in xcode:

YouTubePlayer.swift:339:102: 'UIWebViewNavigationType' has been renamed to 'UIWebView.NavigationType'

Ionic / Angular project

  1. Install the plugin.
npm install --save capacitor-youtube-player@latest
  1. Import plugin in your page.
import { Component, OnInit, AfterViewInit } from '@angular/core';

import { YoutubePlayerWeb } from 'capacitor-youtube-player'; // Web version

import { Plugins, Capacitor } from '@capacitor/core'; // Native version

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit, AfterViewInit {

  currentYear = new Date().getFullYear();

  constructor() {
  }

  ngOnInit() {
  }

  ngAfterViewInit() {
    if (Capacitor.platform === 'web') {
      this.initializeYoutubePlayerPluginWeb();
    } else { // Native
      this.initializeYoutubePlayerPluginNative();
    }
  }

  async initializeYoutubePlayerPluginWeb() {
    const options = {playerId: 'youtube-player', playerSize: {width: 640, height: 360}, videoId: 'tDW2C6rcH6M'};
    const result = await YoutubePlayerWeb.initialize(options);
    console.log('playerReady', result);
  }

  async destroyYoutubePlayerPluginWeb() {
    const result = await YoutubePlayerWeb.destroy('youtube-player');
    console.log('destroyYoutubePlayer', result);
  }

  async initializeYoutubePlayerPluginNative() {

    const { YoutubePlayer } = Plugins;

    const options = {width: 640, height: 360, videoId: 'tDW2C6rcH6M'};
    const playerReady = await YoutubePlayer.initialize(options);
  }

}
  1. Build your app.

You must build your Ionic / Angular project at least once before adding any native platforms.

    ionic build // Ionic
    ng build // Angular
  1. Add Platforms.
    npx cap add ios
    npx cap add android
  1. Open IDE to build, run, and deploy.
    npx cap open ios
    npx cap open android

Examples

Ionic project (Angular)

WEB

Plugin

iOS

Plugin

Android

Plugin

Angular project

Vue project

React project

Keywords

FAQs

Last updated on 30 Nov 2022

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