Skip to content

Instantly share code, notes, and snippets.

@jgrant41475
Last active March 26, 2024 10:54
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jgrant41475/cef689769cab4f647de6982e4ee9833a to your computer and use it in GitHub Desktop.
Save jgrant41475/cef689769cab4f647de6982e4ee9833a to your computer and use it in GitHub Desktop.
Fetches YouTube Video Information and creates a json-ld Video Object
<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Foundation | Welcome</title>
<link rel="stylesheet" href="css/foundation.css" />
</head>
<body>
<div class="row">
<div class="medium-2 columns">&nbsp;</div>
<div class="medium-8 columns">
<div class="YT-Container text-center">
YoutTube Video ID: <input type="text" id="YT-ID">
<div class="button" id="YT-GO">Submit</div>
<div class="button" id="YT-Copy">Copy</div>
</div>
<code id="YT-Data" style="overflow-wrap: break-word;"></code>
</div>
<div class="medium-2 columns">&nbsp;</div>
</div>
<script src="js/vendor/jquery.js"></script>
<script defer>
$(document).ready(function(){
$("#YT-GO").click(function(){
let apiKey = "AIzaSyCVns3Lh4xYBWNgOYeB8LQ5oMLOfL7u6Yw",
part = "snippet,contentDetails,statistics",
id = $("#YT-ID").val()
if(id == null || id.match(/^[a-zA-Z0-9_-]{11}$/) == null)
return $("#YT-Data").text("Invalid YouTube ID.").css("color", "#F00");
$.getJSON(`https://www.googleapis.com/youtube/v3/videos?key=${apiKey}&part=${part}&id=${id}`, function(data){
if (data == null || data.error != null || data.pageInfo.totalResults == 0)
$("#YT-Data").text("Error fetching data.").css("color", "#F00");
else {
let video = data.items[0];
$("#YT-Data").text(
`<div class="video-container"><script type="application/ld+json">{"@context":"http://schema.org","@type":"VideoObject",${reduce({
"name" : video.snippet.title.replace(new RegExp('"', 'g'), '\\"'),
"description" : video.snippet.description.replace(new RegExp('"', 'g'), '\\"'),
"thumbnailUrl" : video.snippet.thumbnails.standard != null ?
video.snippet.thumbnails.standard.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}`,
"commentCount" : video.statistics.commentCount,
"interactionCount" : video.statistics.viewCount
})}}<\/script><div class="youtube-player" data-id="${video.id}"></div></div>`).css("color", "#bababa");
}
});
});
$("#YT-Copy").click(function(){copyToClipboard("#YT-Data");});
});
function reduce(dict, showIndex = true) {
let returnList = [];
for(let [k,v] of Object.entries(dict)) {
if(typeof(v) == "string")
returnList.push(showIndex ? `"${k}":"${v}"` : `"${v}"`);
else if(typeof(v) == "object")
returnList.push(`"${k}":[${reduce(v, false)}]`)
}
return returnList.reduce((a,b) => String(a) + "," + String(b));
}
// https://codepen.io/shaikmaqsood/pen/XmydxJ/
function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}
</script>
</body>
</html>
@Cakemania12
Copy link

Hello! Thank you very much for your piece of code!
I encountered a problem today when I decided to implement structured data for a YouTube video on my website. I was puzzled about the "contentURL" and "embedUrl". So I googled it and found your page with code. That's why I am here:)

So, while the "embedUrl" is clear for me where to get from YouTube, there's a problem with “contentURL”.
Google's guide https://developers.google.com/search/docs/appearance/structured-data/video?hl=en#json-ld doesn't help much since they provide such an example:
"contentUrl": "https://www.example.com/video/123/file.mp4",
"embedUrl": "https://www.example.com/embed/123".
It's useful when the video was downloaded from the file in the server.
But my video is hosted on YouTube, so there is no .mp4 path for it. So I decided to add the following structured data on the page of my website: "contentUrl": "https://www.youtube.com/watch?v=1jee4qFYdP8", "embedUrl": "https://www.youtube.com/embed/1jee4qFYdP8?si=UnP-PsGhOxMGR5jZ"
It's the same as in your code, I suppose:
"contentUrl" : https://youtube.com/watch/?v=${video.id},
"embedUrl" : https://www.youtube.com/embed/${video.id}

I also have found an advice on stackoverflow:
"You can use:
contentUrl: https://youtube.googleapis.com/v/YT_ID
embedUrl: https://www.youtube.com/embed/VT_ID?rel=0"
I am not sure it's relevant for today because there is no correct urls, when I type https://youtube.googleapis.com/v/(ID)...

So finally I need to say that a variant I used passed Google's Validator without any complains. What do you think about that all?
Would be grateful to hear any thoughts or advice! Thanks in advance!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment