Giter VIP home page Giter VIP logo

vue-youtube's Introduction

vue-youtube

VueYoutube

npm vue2 Downloads License

Intro

vue-youtube is an wrapper of YouTube IFrame Player API (YIPA).

What is the difference between other plugins? The difference is that the function body is wrapped in a promise. This promise is resolved only when the player has finished loading and is ready to begin receiving API calls (onReady). Therefore, all function calls are queued and replayed only when player is ready.

You can do something like:

export default {
  // ...
  computed: {
    player() {
      return this.$refs.youtube.player
    }
  },
  methods: {
    async playVideo() {
      await this.player.playVideo()
      // Do something after the playVideo command
    }
  }
}

Live demo built on top of the awesome codesandbox.

Installation

npm install vue-youtube
# or
yarn add vue-youtube

Usage

Bundler (Webpack, Rollup)

import Vue from 'vue'
import VueYoutube from 'vue-youtube'

Vue.use(VueYoutube)

Browser

<!-- Include after Vue -->
<!-- Local files -->
<script src="vue-youtube/dist/vue-youtube.js"></script>

Example

<youtube :video-id="videoId" ref="youtube" @playing="playing"></youtube>
<button @click="playVideo">play</button>
export default {
  data() {
    return {
      videoId: 'lG0Ys-2d4MA'
    }
  },
  methods: {
    playVideo() {
      this.player.playVideo()
    },
    playing() {
      console.log('\o/ we are watching!!!')
    }
  },
  computed: {
    player() {
      return this.$refs.youtube.player
    }
  }
}

or

<youtube :video-id="videoId" :player-vars="playerVars" @playing="playing"></youtube>
export default {
  data() {
    return {
      videoId: 'lG0Ys-2d4MA',
      playerVars: {
        autoplay: 1
      }
    }
  },
  methods: {
    playing() {
      console.log('\o/ we are watching!!!')
    }
  }
}

Live demo

Events

The component triggers events to notify the parent component of changes in the player. For more information, see YouTube IFrame Player API.

Events => ready ended playing paused buffering cued error

Player

You have access to all api methods through component referencing.

Example:

<youtube video-id="lG0Ys-2d4MA" ref="youtube"></youtube>
export default {
  // ...
  methods: {
    playVideo() {
      this.$refs.youtube.player.playVideo()
    }
  }
}

Props

Prop Type(s) Default Description
width Number, String 640 iframe pixel width
height Number, String 360 iframe pixel height
resize Boolean false iframe will proportionally scale height with its width
resizeDelay Number 200 Delay in milliseconds before running resize callback
fitParent Boolean false iframe will use its parent's width
nocookie Boolean false Change host param to www.youtube-nocookie.com

Tips for Resizing

Resizing proportionally (resize) works best with a parent element. The parent element is used for a width reference. fitParent should be on in most situations. It allows resize to work without appyling CSS any properties to your iframe. If you want to turn fitParent off, you can emulate it with CSS by setting width to 100%, like so:

iframe {
  width: 100%;
  max-width: 650px; /* Also helpful. Optional. */
}

API

vm.$youtube.getIdFromUrl

New in v1.2.0

  • Type: Function
  • Description: Parse a youtube url returning the video ID. (get-youtube-id)
  • Arguments:
    • {String} url
    • {Object} options
  • Usage:
...
  methods: {
    getId () {
      return this.$youtube.getIdFromUrl(this.video.url)
    }
  }
...

or

import { getIdFromUrl } from 'vue-youtube'

const myFunction = (url) => {
  const youtubeId = getIdFromUrl(url)
  // ...
}

License

MIT

vue-youtube's People

Contributors

anteriovieira avatar dependabot[bot] avatar digitalfrost avatar frank3k avatar jhrr avatar rangermeier avatar tarikhamilton avatar tassilogroeper avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vue-youtube's Issues

Computing this.player.getCurrentTime()

Hi, thanks a lot for this wrapper for the Youtube API.

I'm having some trouble figuring out how to display a timestamp in my UI that updates as the video is playing (00:01, ...), because using setTimeout doesn't work due to this.player.getCurrentTime() being a Promise.

Any idea on how to do this?

Missing @types/vue-youtube

Hello,

I am using this great library with typescript and VS Code is warning about missing declaration file.

Acces to getDuration()

Hello,

Thank you for your work on this component.
I try to access to getDuration(), according to the Youtube API. But i can not get the value, it returns me a function as a string. When I try to log I get a ReactiveGetter().
I made a demo here : https://codesandbox.io/s/9vwmmz30r

M.

www-widgetapi.js:115 Failed to execute 'postMessage' on 'DOMWindow

Hello,

I have been using your plugin and keep getting this error in the chrome console.

www-widgetapi.js:115 Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('https://www.youtube.com') does not match the recipient window's origin ('https://mysite.com').

Maybe this link can help you fix the issue in your code:
https://stackoverflow.com/questions/27573017/failed-to-execute-postmessage-on-domwindow-https-www-youtube-com-http

I am using the version 1.3.5

Thank you.

How to set the size of the Iframe?

Hi ,

How to can i set the size of the Iframe?
I have to make it responsive and the following does not work. Can someone help?
v-layout row>
v-flex xs12 sm6 offset-sm3>
<youtube :video-id="getId" ref="youtube" @playing="playing">
v-flex>
v-layout>

Play video asynchronously when changing video id

How to play an video after the player is ready?

My app has buttons for load different videos in an unique instance of vue-youtube. I need click in some button and after player loaded, i need play this video.

v-if and vue-youtube

Heyho!

I wanted to hide the vue-youtube component by using a simple v-if. Unfortunately, I wasn't able to recover the iFrame properly.

I tried to create a JSFiddle so you see what I mean, but because of the require call in your dist js file it doesn't work out. So here is the code I'm using:

<template>
  <button @click="reEnableVideo">
    Film nochmal abspielen
  </button>
  <youtube :video-id="videoId" :player-vars="playerVars"
    @ended="videoEnded"  allowfullscreen ref="youtube"
    v-if="!hasEnded"></youtube>
</template>

<script>
  export default {
    data () {
      return {
        videoId: 'BBJa32lCaaY',
        playerVars: {
          showInfo: 0
        },
        hasEnded: false
      }
    },
    computed: {
      player () {
        return this.$refs.youtube.player
      }
    },
    methods: {
      videoEnded () {
        this.hasEnded = true
      },
      async reEnableVideo () {
        this.hasEnded = false
        await new Promise((resolve) => { setTimeout(resolve, 1050) })
        this.player.playVideo()
      }
    }
  }
</script>

Failed to execute 'postMessage' on 'DOMWindow'

Embedding video to the page causes this error in the console:
Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('https://www.youtube.com') does not match the recipient window's origin (*host name*)

You can even see this error in the console on the demo page of the plugin.

Add nocookies prop to add the host option “https://www.youtube-nocookie.com”

Problem

To use Youtube GDPR compliant, I don't want to use the default config of the youtube player. Rather use the nocookie-domain:

direct implementation:

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

player = new YT.Player('player1', {
	    wmode: 'transparent',
            host: 'https://www.youtube-nocookie.com',
	    playerVars:{
		   wmode: 'transparent',
		   showinfo:0,
		   autohide:1,
            },
	  videoId: YOUR_VID_ID,
	  events: {
		  'onReady': onPlayerReady
		}
        });

https://portalzine.de/dev/api/youtube-iframe-api-and-cookieless-domain-solution-gdpr-dsgvo/

How to fix?

Add a new prop nocookie boolean flag and set the host accordingly.

How to adapt vue-youtube to use with Vuex

Hi, i'm using vuex in my project and but i can't make your component work with it, i always get the issue 'Unknown custom element: - did you register the component correctly? For recursive components, make sure to provide the "name" option.'

Do you a have a solution for that?

Option to use youtube embed with privacy enhanced mode (-nocookie youtube)

Currently all the plays on the embedded youtube video will get tracked and stored in user's youtube watch history, this might not be an intended behaviour of many apps.

Adding an option to disable this would be awesome, and I think this can be implemented simply by adding -nocookie to the youtube embed URL, such as https://www.youtube-nocookie.com/embed/O17OWyx08Cg.

More about this mode can be found here

Not compatible with Vue 3 RC

Running into the following issue trying to use vue-youtube on Vue 3 RC

Installed vue-youtube via npm, and imported it into my project globally in main.js following the directions given by the Vue 3 docs.

main.js

import { createApp } from 'vue'
import App from './App.vue'
import VueYoutube from 'vue-youtube'

createApp(App)
  .use(VueYoutube)
  .mount('#app')

In the console, I get the following error:

Uncaught TypeError: Cannot set property '$youtube' of undefined

Might be something minor?

event methods suddenly stopped working

Hello, i am developing an app using this package. i tested it yesterday and everything was working fine. when i worked on the app again, the player event method suddenly stopped working. other user defined methods is still working properly but the video defined methods just stopped working

How to assign video id to variable and play it in one step?

Hi. Thank you for this component.

I have little issue - I want to make input field for YouTube video ids and by clicking on a button "play" I want to start video playing. The problem is the next: when I click "play", I see that ID is assigned to videoId, but in order to actually start a video playing, I need to click "play" again.

However if videoId is hardcoded (videoId: 'lG0Ys-2d4MA', how it is shown in your examples), video starts by the 1st click on 'play'. Also if input's v-model="videoId" (not providedId) video is downloading immediately and by clicking on play it starts to play, but I do not need auto-downloading once input is changed - I want to download video just by clicking on play.

Below is the minimal reproducible example

template

<input type="text" v-model="providedId"/>
<button @click="playVideo">play</button>
<youtube :video-id="videoId" ref="youtube"></youtube>

script

export default {
  data () {
    return {
     videoId: '', // <<-- empty srting
    providedId: ''
    }
  },
  methods: {
    playVideo () {
      this.videoId = this.providedId // <<-- assign video id
      this.player.playVideo()
    },
  },
  computed: {
    player () {
      return this.$refs.youtube.player
    }
  }
}

Can you please help me to solve this issue?
Thanks.

How to set video quality?

console.log($vm0.player.getPlaybackQuality())
console.log($vm0.player.getPlaybackQuality())
$vm0.player.stopVideo()
$vm0.player.setPlaybackQuality('small')
$vm0.player.playVideo()
console.log($vm0.player.getPlaybackQuality())

image

Error event returns event target, not error code

When the onError event fires, I would like to access the error code, however this plugin currently returns only the event.target, which—as far as I can tell—is only the YouTube player object without any internal error logs.

The YouTube API says that the error code is available via event.data.

This plugin (playerError()): https://github.com/anteriovieira/vue-youtube/blob/master/src/vue-youtube.js#L68
YouTube API (onError()): https://developers.google.com/youtube/iframe_api_reference#onError

Access to onPlaybackRateChange event

Hi, first of all, thank you for this great project.

I apologize if I just missed something in the docs about how to do this, but it seems that some of the events from the youtube api are not accessible directly through vue-youtube with an @event binding in the template. As the subject of this email imples, I'm specifically interested in onPlaybackChange - although onStateChange would be nice too.

I do see that you have access to the addEventListener method of the player, which allows you to add the name of function to call. So, something like, this.player.addEventListener('onPlaybackChange', 'myFunction'). But, as far as I can tell the 'myFunction" needs to live on the global window. Maybe there is a better way to do this, but for now I'm putting a function on "window", which is not ideal.

Once again thanks.

Blurry Thumbnail

Hi @anteriovieira ,
since some days my thumbnails are blurry.
I already found this: https://support.google.com/youtube/thread/8920318?hl=en
I also found "somehow" a solution to fix this, by using the high resolution thumbnail.
This is working fine if I inspect the HTML Code and change the thumbnail url manually.

Is there a way to change the thumbnail url within your component? I was unable to find anything regarding this.

If not: Is there any plan to implement this?
vue-yt

Use on CodePen?

I'm 90% sure this is my fault and not yours. ;) I'm trying to use this in a CodePen demo. In my settings I've added https://raw.githubusercontent.com/anteriovieira/vue-youtube/master/dist/vue-youtube.js as a dependency. But any use of VueYoutube returns an error because it isn't defined. According to CodePen, any external JS libraries are loaded before your code is executed so I'm not quite sure what's wrong. Any ideas?

Playlist

Antério, very nice plugin! I'd like to use a playlist ID instead of video ID, whats the way?

Antério, muito bom seu plugin, estou utilizando ele no momento, porém gostaria de saber se é possível usar uma ID de playlist.

Vue.component is not a function

Having a issue using VueYoutube component in single file component.
I am using props for :video-id. Modal.vue component is than used in another Component file. But the error is 'created' in Modal.vue.
With VueJS i am using NuxtJS.

vue-youtube version is ^1.3.4. & nuxt is 2.0.0

components/Modal.vue:

<template>
    <div class="modal-backdrop">
        <i class="icon ion-ios-close close-icon" @click="close"></i>
        <div class="modal">
            <VueYoutube :video-id="videoLink" ref="youtube"></VueYoutube>
        </div>
    </div>
</template>

<script>
import VueYoutube from 'vue-youtube';

export default {
    name: 'Modal',
    // Methods
    methods: {
        close() {
            this.$emit('close');
        },
        playVideo() {
            this.player.playVideo();
        }
    },
    // Props
    props: ['videoLink'],
    components: {
        VueYoutube
    },
    computed: {
        player() {
            return this.$refs.youtube.player;
        }
    }
};
</script>

VueJS Throws This Error:
Screenshot_1

Any possible solution for this?

Event "ended" triggered multyple times.

I have player:

<youtube :video-id="videos[id].videoId" :player-vars="videos[id].playerVars" @ended="nextVideo()" />

And function:

nextVideo(){
      this.id+=1
      console.log('Triggered')
},

When video with custom end time ends, I see 2 or 3 "Triggered" in console.

All functions seem to return pending promises that never resolve

Hi,

I'm trying to use this wrapper in my new project, however I've run into a problem - the player itself works exactly as intended, but I can't control it in code.

Extremely simple example:

      <youtube :video-id="videoId" ref="youtube" width="600" height="400" :player-vars="playerVars"></youtube>
      <button @click="play">PLAY</button>
methods: {
   play () {
     this.$refs.youtube.player.playVideo()
   }
}

The player itself works - I can click it to start the video, skip around, et cetera. However, the play() method does nothing. All it returns is an empty, pending promise

Have I missed something? I'm assuming that were the promises to resolve, it would allow me to control the player.

playVideo() function doesn't work in computed or watch function!

Hi,

I try to call some function like playVideo() inside a watcher (i want the video reload when videoId change).
I don't know why, but it doesn't work! If i call it from mounted() lifehook, or from a click action it work like expected, but not if i pass by watchers.

I'm sure you know why! i thinks it's because i need to do something more to be sure that player is ready, like for getCurrentTime function.

Thanks.

EDIT : Sorry, i found a solution using the updated lifehook and that works nice! But i'm still curious of why this is working in mounted/updated function but not in computed/watchers?

Cannot read property 'getIdFromUrl' of undefined

I really commend the great effort put into this package.

I'm currently using version 1.3.4

I have a method as below

getId() { return this.$youtube.getIdFromUrl(this.videoUrl); }

The out output of console.log(this.$youtube); is shown in the attached screenshot

Screenshot 2019-05-19 at 5 22 48 AM

Please how can i resolve this?

Unable to post message to https://www.youtube.com.

Hi. I'm testing your component. I found this error in browser console:

Unable to post message to https://www.youtube.com. Recipient has origin http://localhost:8081.

Could you explain what it means and how to fix it? What „message” does it want to post?

resize/fitparent props not working

I'm having trouble resizing the iframe using the resize or fitparent props. Here is the code I used.

<div style="width: 100%">
<youtube :video-id="videoId" ref="youtube" @playing="playing" fitparent=true ></youtube>
</div>

<youtube :video-id="videoId" ref="youtube" @playing="playing" width="100%" resize=true ></youtube>

Detailed event hook example

Hello. Have only been using vue.js for 1-2 days. Could you provide a more detailed example of hooking the 'playing' event with a callback?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.