PlayerJs.js
2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
(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));
};
}());