Created
September 14, 2017 02:18
-
-
Save tonY1883/a3b85925081688de569b779b4657439b to your computer and use it in GitHub Desktop.
A small trick to check if youtube video exist with its id.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function validVideoId(id) { | |
var img = new Image(); | |
img.src = "http://img.youtube.com/vi/" + id + "/mqdefault.jpg"; | |
img.onload = function () { | |
checkThumbnail(this.width); | |
} | |
} | |
function checkThumbnail(width) { | |
//HACK a mq thumbnail has width of 320. | |
//if the video does not exist(therefore thumbnail don't exist), a default thumbnail of 120 width is returned. | |
if (width === 120) { | |
alert("Error: Invalid video id"); | |
} | |
} |
This has saved my sanity, thank you for this! My codebase is in PHP so I took the liberty of taking the principle and rewriting it. I may as well paste here what I did for if anyone needs it!:
function getYouTubeThumbnailDimensionsByID(string $id): Array {
$image_curl = curl_init();
curl_setopt($image_curl, CURLOPT_URL, "http://img.youtube.com/vi/$id/mqdefault.jpg");
curl_setopt($image_curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($image_curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
$image_result = curl_exec($image_curl);
$image = imagecreatefromstring($image_result);
return [
"x" => imagesx($image),
"y" => imagesy($image)
];
}
Then of course just check if x == 120
.
There are exceptions, but it's still the best way to simply check in Javascript. I tried to compare sha1 hash values with difficulty.
Thank you.
Thank you for the trick, saved my day
you beauty! I've found nothing else that works.
thanks man it works
my approach is this btw :
im using venilla js.
const is_valid_ytd_video = async (id) => {
let response = await axios.request("https://www.youtube.com/embed/" + id)
return response.data.toLowerCase().includes("Video unavailable".toLowerCase());
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This will work EXCEPT for a very small number of Youtube IDs that do exist, but nevertheless lack a preview image and have that 120px-wide one instead. Typically this is because the account owner had deleted them then undeleted them, and sometimes the preview images don't come back. An example is this one: "iUjUnrpsp6I".
I just remove them from the results manually like so, but maybe there's a better way:
function validVideoId(id) {
var img = new Image();