Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the YouTube iFrame API in Chrome and Firefox?

I have a YouTube video embedded on my site using an iFrame. I want to use the API to pause the video, but in Chrome I get an error:

Unsafe JavaScript attempt to access frame with URL http://subdomain.example.com/ from frame with URL http://www.youtube.com/embed/KmtzQCSh6xk?enablejsapi=1&origin=http://subdomain.example.com. Domains, protocols and ports must match.

In Firefox (3.6) I get this error:

Permission denied for <http://www.youtube.com> to call method Location.toString on <http://subdomain.example.com>.

I've tried putting the iFrame in myself or adding it with the API. Either way the player gets in, but I have no API control over it.

Here's the relevant part of my code:

<div id="player"></div>

<script type="text/javascript">
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var player;
function onYouTubePlayerAPIReady() {
    player = new YT.Player('player', {
        height: '433',
        width: '731',
        videoId: 'KmtzQCSh6xk'
      });
}

$("#pause_button").click(function(){
  alert("Pausing " + player);//is undefined :(
  player.pauseVideo();
});

</script>

How do I get browsers to allow the YouTube iFrame to access my page's main frame?

Thanks!

like image 895
Adam Avatar asked Feb 10 '11 00:02

Adam


1 Answers

  1. Ignore those warnings. The player should still work fine regardless.

  2. Use the recently-introduced JavaScript Player API for iframe embeds.

like image 160
a paid nerd Avatar answered Oct 17 '22 18:10

a paid nerd