Last active
March 3, 2022 20:47
-
-
Save DinoscapeProgramming/3ea5113bca8a54f6cb00d9b816af76b9 to your computer and use it in GitHub Desktop.
A simple trick to check is a video existing or not
This file contains hidden or 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
// definition | |
function videoExists(url) { | |
var exists; | |
var video; | |
try { | |
video = new URL(url); | |
} catch { | |
throw new Error("Invalid URL 😳") | |
} | |
var img = new Image(); | |
img.src = "https://img.youtube.com/vi/" + video.searchParams.get('v') + "/mqdefault.jpg"; | |
img.onload = function () { | |
exists = !this.width === 120 && !this.height === 90; | |
} | |
img.onerror = function () { | |
throw new Error("Hmm... Something went wrong :("); | |
} | |
return exists; | |
} | |
// usage | |
videoExists("https://www.youtube.com/watch?v=notExisting") // returns false | |
videoExists("https://www.youtube.com/watch?v=--AuxdQUdlo") // returns true | |
// advanced usage | |
if (videoExists("YOUR VIDEO")) { | |
console.log("This video exists") | |
} else { | |
console.log("I can't found this video :(") | |
} | |
// credits | |
/* | |
* Credits to YouTube and GitHub | |
**/ | |
// note | |
/* | |
* This code is free to use | |
**/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I hope I can help you with your program or anything else :)