Skip to main content

Play youtube video in Ionic Framework App

We can add YouTube videos in our simple ionic app by creating simple directive in angularjs and pass the youtube video id.

I have refer multiple sites and solutions and after that create one directive and use it in my app to embed youtube video in ionic app.

1.Create the project

ionic start Test blank
cd Test
ionic platform add android

2.Implementation

Here is how most people add a YouTube player to their hybrid app :

<iframe src="https://www.youtube.com/embed/KBKXu3Kg4yg?rel=0" frameborder="0" allowfullscreen>
</iframe>

This is simple way but here we ar not handle some events with youtube video and it's may be complicated for us.For that we creating directive and use it our view.
First head out to google development docs and look up the programmatic way of embedding YouTube using javascript.

Following code shows the code in our directives.js file

angular.module('starter.dirctives', [])
.directive('youtube', function($window) {
 return {
   restrict: "E",

   scope: {
     height: "@",
     width: "@",
     videoid: "@"
   },

   template: '<div></div>',

   link: function(scope, element) {
     var tag = document.createElement('script');
     tag.src = "https://www.youtube.com/iframe_api";
     var firstScriptTag = document.getElementsByTagName('script')[0];
     firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

     var player;

     $window.onYouTubeIframeAPIReady = function() {

       player = new YT.Player(element.children()[0], {
         playerVars: {
           autoplay: 0,
           html5: 1,
           theme: "light",
           modesbranding: 0,
           color: "white",
           iv_load_policy: 3,
           showinfo: 1,
           controls: 1
         },

         height: scope.height,
         width: scope.width,
         videoId: scope.videoid,
       });
     }

     scope.$watch('videoid', function(newValue, oldValue) {
       if (newValue == oldValue) {
         return;
       }

       player.cueVideoById(scope.videoid);

     });

     scope.$watch('height + width', function(newValue, oldValue) {
       if (newValue == oldValue) {
         return;
       }

       player.setSize(scope.width, scope.height);

     });
   }  
 };
});


Following code shows the code in our controllers.js  file

angular.module('starter.controllers', [])
.controller('youtubevideo', function($scope, $sce) {
   $scope.navTitle = 'Video Gallery';
$scope.yt = {
     videoid: "M7lc1UVf-VE",
   };
});

Following code shows the code in our app.js  file

angular.module('starter', ['ionic', 'starter.controllers',  'starter.dirctives'])

.run(function($ionicPlatform) {
 $ionicPlatform.ready(function() {
   // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
   // for form inputs)
   if (window.cordova && window.cordova.plugins.Keyboard) {
     cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
   }
   if (window.StatusBar) {
     // org.apache.cordova.statusbar required
     StatusBar.styleDefault();
   }
 });
})

.config(function( $sceDelegateProvider) {
$sceDelegateProvider.resourceUrlWhitelist(['self', new RegExp('^(http[s]?):\/\/(w{3}.)?youtube\.com/.+$')]);
});

Following code shows the code in our index.html file

<!DOCTYPE html>
<html>
 <head>
   <meta charset="utf-8">
   <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
   <title></title>

   <!-- compiled css output -->

   <link href="css/ionic.app.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
   <!-- ionic/angularjs js -->
   <script src="lib/ionic/js/ionic.bundle.js"></script>

   <!-- cordova script (this will be a 404 during development) -->
   <script src="cordova.js"></script>
   <script src="lib/ng-cordova.min.js"></script>
   <!-- your app's js -->
   <script src="js/app.js"></script>
   <script src="js/controllers.js"></script>
<script src="js/dirctives.js"></script>
 </head>

 <body ng-app="starter">
   <ion-view view-title="Video Gallery">
<ion-content>
<div class="list card">
<div class="item item-divider">
<i class="ion-videocamera"></i>
Video
</div>
<div class="padding">
 <youtube width="100%" height="150" videoid="{{yt.videoid}}"></youtube>  
</div>
</div>  
</ion-content>
</ion-view>
 </body>
</html>

3.Run it


ionic build android

NOTE:

At the time running application i have got one error like URL blocked by  whitelist on Android and it solved by adding plugin.
With the updated version of cordova-android, you now need to include the cordova-whitelist-plugin.

Comments

  1. Hi santosh,

    I tried the solution mentioned in this blog and http://stackoverflow.com/questions/37516486/how-to-play-restricted-playback-youtube-videos-on-android-using-ionic-framework. Both are giving same exception that playback is restricted in certain sites on my android device. Is there any solution for that.

    ReplyDelete

  2. Thanks for sharing, I will bookmark and be back again

    hire ionic developers

    ReplyDelete

Post a Comment

Popular posts from this blog

What exactly means MVW design pattern ?

What is a MVW framework? The abbreviation stands for 'Model - View - Whatever'.  Well there are many different JavaScript frameworks available , all invented for the same purpose. They all try to separate the presentation logic from the business logic where JavaScript holds the model and logic, and html the presentation layer. Quick overview : You can change the model without changing the view and vice-versa Unit testing is easy These are the core benefits of using such a framework. By separating presentation and business logic changes to the code are easier to implement and take less time. Another benefit is that code can be reused from a controller thus saving more time. Angularjs makes the code also shorter in comparison to other frameworks, which improves code stability. Less code means minor potential for bugs. For several years +AngularJS was closer to MVC (or rather one of its client-side variants), but over time and thanks to many refactorings...

File Upload & Download With ng-cordova File Transfer Plugin In Ionic Framework

Using the AngularJS extension set , ngCordova , with Ionic Framework and the Apache Cordova File Transfer plugin, you can easily upload files to a remote server and download files from a remote server. 1.Create the project ionic start Test blank cd Test ionic platform add android 2.Add Plugin org.apache.cordova.file-transfer https://github.com/apache/cordova-plugin-file-transfer This plugin allows you to upload and download files. This plugin defines global FileTransfer, FileUploadOptions Constructors. Although in the global scope, they are not available until after the deviceready event . Installation cordova plugin add cordova plugin add cordova-plugin-file-transfer     2.    org.apache.cordova.file             https://github.com/apache/cordova-plugin-file             This plugin implements a Fi...

Steps To Create Cordova Plugin

Introduction A plugin is a package of injected code that allows the Cordova webview within which the app renders to communicate with the native platform on which it runs. Plugins comprise a single JavaScript interface along with corresponding native code libraries for each supported platform. Due to following reason, we will go for plugin development To get the native capabilities of the device in the cordova based app Build the common functionality across the number of Cordova application(Reusability) Prerequisites For the creation of plugin you need to install plugman . npm install -g plugman Plugin Structure Decide Plugin ID & Name The plugin ID should be unique Plugin name should follow the convention “cordova.plugin.[your.plugin.name]” Create the structure Use the following command to create the plugin with plugin ID “cordova.plugin.test” and name “Test”. plugman create --name Test --...