(function () { var PlayerJs = window.PlayerJs = function (id) { this.el = document.querySelectorAll(id)[0]; this.origin = this.el.src; }; PlayerJs.prototype.play = function () { this._send('play'); }; PlayerJs.prototype.pause = function () { this._send('pause'); }; PlayerJs.prototype.onReady = function (callback) { PlayerJsReady.listen(this.el, callback); }; PlayerJs.prototype._send = function (method, value) { /** * We only want to send messages if player is ready to receive them. */ this.onReady(function () { this.el.contentWindow.postMessage( JSON.stringify({ context: 'player.js', version: '0.0.11', method: method, value: value, }), this.origin ); }.bind(this)); }; /** * Subscribes listener for an event coming from player. * * @todo Optimize to use only one window.addEventListener. * * @param {string} eventName The event name * @param {Function} callback The callback * @return {Function} Listener that can be used to later unsubscribe. */ PlayerJs.prototype._on = function (eventName, callback) { var listener = function (e) { if (e.source !== this.el.contentWindow) { return; } var message = PlayerJsCommon.getPlayerJsMessage(e); if (!message || message.event !== eventName) { return; } callback(message, e); }.bind(this); window.addEventListener('message', listener); return listener; }; PlayerJs.prototype._off = function (listener) { window.removeEventListener('message', listener); }; PlayerJs.prototype.onFirstPlay = function (callback) { /** * Ask player inside iframe to send 'play' events. */ this._send('addEventListener', 'play'); var firstPlayListener = this._on('play', function () { /** * Make sure this callback is ran only once. */ this._off(firstPlayListener); callback(); }.bind(this)); }; }());