Reputation: 103
I have a website with several internal (i.e. without src) iframes inside, where I want to include a Youtube player (using its API). In short, I want players inside iframes, managed by the parent page.
Problem is that the code initialization, AFAIK, is not working with iframes. For example:
var player = new YT.Player('video-player1', {});
The problem, as you might have guessed, is that you can't define the document in which that ID is contained. In jQuery, I would use something like:
$("video-player1", frames["iframe1"].document)
Is there any workaround for this? The only solution I can see is, obviously, loading the YT api in every iframe and working inside of any iframe, but that would mean refactorizing a lot of logic from my application, besides the additional cost of several loads of the Youtube JS files.
Upvotes: 3
Views: 1553
Reputation: 1668
I'm sorry mate. The solution to your problem is "easy" to code/implement but painful and difficult to maintain.
Youtube API does not allow to embed a YT.Player object within an Iframe (e.g. div within an iframe), because it looks for the 'player' node within the window object and not in the iframe document.
So, a quick hotfix for this would be to save a copy of the API files and modify them to add this functionality. Obviously, from that moment on, it is your responsability to serve these files and also to update them in order the files do not get deprecated.
The solution would be (I take for granted JQuery is loaded before Youtube API):
Using the base example provided at https://developers.google.com/youtube/iframe_api_reference#Getting_Started I guess you have this
<iframe id="if"></iframe>
instead of <div id="player"></div>
and that later on you append the player div inside that iframe.
<body>
<iframe id="if"></iframe>
<script>
$('#if').contents().find('body').append($('<div id="player"></div>'));
// ...
So, whem defining onYoutubeAPIReady()
, you must add 1 parameter to the YT.Player
constructor:
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', { /* options */ }, $('#if') );
That is $('#if')
, the iframe element where you want to embed the player.
iframe_api
In this file you just need to modify the src of the script it loads:
from
a.src = 'http://s.ytimg.com/yts/jsbin/www-widgetapi-vflOb0oo1.js
to a.src = './widget.js';
(widget.js is your copy of www-widgetapi-vflOb0oo1.js).
Finally on widget.js:
Here you must modify this 2 functions: function S(a,b)
and function Y(a,b)
.
First function Y(a,b)
to function Y(a,b,c)
in order to get the iframe parameter. Then in its body you change S.call(this,a,new nb(b));
to S.call(this,a,new nb(b),c);
Second, function S(a,b)
to function S(a,b, dom)
and c = document
to
c= dom === undefined ? document : dom.contents()[0]
.
Now you have a Youtube player inside your iframe and you are able to use it from the parent window.
I hope it is useful! ;)
Upvotes: 3