-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
106 lines (87 loc) · 3.49 KB
/
Copy pathscript.js
File metadata and controls
106 lines (87 loc) · 3.49 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
(function () {
const API_KEY = "AIzaSyAmCT442N0C8wPfABglR_YrWzhppE_wlhk";
const API_URL = "https://www.googleapis.com/youtube/v3/videos";
const form = document.getElementById('submit-form');
const code = document.getElementById('video-json');
const copyBTN = document.getElementById('copy-to-clipboard');
if (!form || !code || !copyBTN) {
return;
}
form.addEventListener('submit', (event) => {
event.preventDefault();
form.classList.remove('error');
const userURLField = form.elements['youtube-link'];
if (!userURLField) {
form.classList.add('error');
return;
}
const videoURLParams = new URLSearchParams(new URL(userURLField.value).search);
const videoID = videoURLParams.get('v');
if (!videoID) {
form.classList.add('error');
return;
}
fetchYTVideoInfo(videoID)
.then((videoData) => {
const video = videoData.items[0];
if (!video) {
form.classList.add('error');
return;
}
let json = JSON.stringify({
"@context": "https://schema.org",
"@type": "VideoObject",
"name": video.snippet.title,
"description": video.snippet.description.replace(/[\r\n]+/g, ' '),
"thumbnailUrl": video.snippet.thumbnails.maxres != null ?
video.snippet.thumbnails.maxres.url :
video.snippet.thumbnails.default.url,
"uploadDate": video.snippet.publishedAt,
"duration": video.contentDetails.duration,
"keywords": video.snippet.tags,
"contentUrl": `https://youtube.com/watch/?v=${video.id}`,
"embedUrl": `https://www.youtube.com/embed/${video.id}`
}, null, 4);
code.innerHTML = '<script type="application/ld+json">' + json + '</script>';
})
.catch(error => {
console.error('There was a problem with the fetch operation:', error);
form.classList.add('error');
});
});
copyBTN.addEventListener('click', (event) => {
event.preventDefault();
const valueToCopy = code.value;
if (valueToCopy != '') {
navigator?.clipboard?.writeText(valueToCopy)
.then(
() => {
copyBTN.classList.add('success');
setTimeout( () => {
copyBTN.classList.remove('success');
}, 5000);
},
() => {
copyBTN.classList.add('failed');
setTimeout( () => {
copyBTN.classList.remove('failed');
}, 5000);
}
);
}
});
const fetchYTVideoInfo = async (id) => {
const queryParams = new URLSearchParams({
key: API_KEY,
part: 'snippet,contentDetails,statistics',
id: id
}).toString();
return fetch(`${API_URL}?${queryParams}`)
.then(response => {
if (!response.ok) {
throw new Error('YT response was not ok');
}
return response.json();
});
};
})();