Youtube Player iFrame API
by MegaScience
HTML
<script src="https://www.youtube.com/iframe_api"></script>
<div id="player"></div>
<input name="url" type="text"/>
JavaScript
const gYTID = {
re: {},
init: function () {
this.re.proto = new RegExp(`^[a-zA-Z]+:\/\/`)
this.re.videoStr = '([a-zA-Z0-9\-_]+)'
this.re.videoReg = new RegExp(`^${this.re.videoStr}$`)
this.re.pathEnd = new RegExp(`\/${this.re.videoStr}$`)
this.re.pathEndF = (u, p) => {
const o = { 'success' : true}
const videoID = this.re.pathEnd.exec(u[p])
if(videoID && videoID[1]) o.videoID = videoID[1]
else {
o.success = false
o.reason =`Domain "${u.hostname}" has incorrect ${p}: ${u[p]}`
}
return o
}
return this
},
getYouTubeID: function(ad) {
let o = { 'success' : true, 'videoID' : false }
const URLObj = this.getURLObject(ad)
try {
if(!URLObj) throw `URL was not valid.`
const LCHN = URLObj.hostname.toLowerCase()
if(LCHN.toLowerCase().endsWith('youtu.be')) {
o = this.re.pathEndF(URLObj, 'pathname')
if(!o.success) throw o.reason
}
else if(LCHN.endsWith('youtube.com')) {
const LCPN = URLObj.pathname.toLowerCase()
if(LCPN.startsWith('/watch')) {
const videoID = URLObj.searchParams.get('v') || URLObj.searchParams.get('vi') || null
if(videoID && this.re.videoReg.test(videoID)) o.videoID = videoID
else throw `Valid Video ID not found in Watch Page Query: ${URLObj.search}`
}
else if(LCPN.startsWith('/v') || LCPN.startsWith('/vi') || LCPN.startsWith('/embed')) {
o = this.re.pathEndF(URLObj, 'pathname')
if(!o.success) throw o.reason
}
else if(LCPN.startsWith('/user') && URLObj.hash.length) {
o = this.re.pathEndF(URLObj, 'hash')
if(!o.success) throw o.reason
}
else throw `Unsupported YouTube Page.`
}
else throw `Unsupported Domain: ${URLObj.hostname}`
}
catch(e) {
o.success = false
o.reason = e
}
return o
},
getURLObject: function (ad) {
try {
if(!this.re.proto.test(ad)) ad = 'http://' + ad
return new URL(ad)
}
catch(e) {
return false
}
}
}.init()
let player = false
function onYouTubeIframeAPIReady() {
...