-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathvideo-inline-embed.es6.js
More file actions
87 lines (74 loc) · 2.37 KB
/
video-inline-embed.es6.js
File metadata and controls
87 lines (74 loc) · 2.37 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
85
86
87
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
/* eslint no-unused-vars: [2, { "varsIgnorePattern": "onYouTubeIframeAPIReady" }] */
// YouTube API hook has to be in global scope
window.onYouTubeIframeAPIReady = function () {
// Play the video only once the API is ready.
Mozilla.YouTubeInlineEmbed();
};
const src = 'https://www.youtube.com/iframe_api';
let videoLink;
let videoId;
let videoStart;
function loadScript() {
const tag = document.createElement('script');
tag.src = src;
const firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
}
function isScriptLoaded() {
return document.querySelector('script[src="' + src + '"]') ? true : false;
}
function playVideo() {
// return early if youtube API fails to load or is blocked.
if (typeof window.YT === 'undefined') {
return;
}
new window.YT.Player(videoLink, {
host: 'https://www.youtube-nocookie.com', // privacy-enhanced mode
width: 640,
height: 360,
videoId: videoId,
playerVars: {
start: videoStart,
modestbranding: 1, // hide YouTube logo.
rel: 0, // do not show related videos on end.
cc_load_policy: 1 // show captions.
},
events: {
onReady: onPlayerReady
}
});
function onPlayerReady(event) {
event.target.playVideo();
}
}
function initVideoPlayer() {
// check to see if you youtube API is loaded before trying to play the video.
if (!isScriptLoaded()) {
loadScript();
} else {
playVideo();
}
}
function init() {
const videos = document.querySelectorAll('.js-video-play');
for (let i = 0; i < videos.length; i++) {
videos[i].setAttribute('role', 'button');
videos[i].addEventListener('click', (e) => {
e.preventDefault();
videoLink = e.currentTarget;
videoId = videoLink.getAttribute('data-video-id');
videoStart = parseInt(
videoLink.getAttribute('data-video-start'),
10
);
initVideoPlayer();
});
}
}
Mozilla.YouTubeInlineEmbed = playVideo;
init();