aboutsummaryrefslogtreecommitdiffhomepage
path: root/utils.js
blob: 2134c1af804e8dd8e1a2c745ce915e66fd340199 (plain)
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
function getYouTubeVideoID(url) {

    //Attempt to parse url
    try { 
        var obj = new URL(url);
    } catch (e) {      
        console.error("[SB] Unable to parser URL");
        return false
    }
  
    //Check if valid hostname
    if(!["www.youtube.com","www.youtube-nocookie.com"].includes(obj.host)) return false; 
    
    if (obj.pathname == "/watch" && obj.searchParams.has("v")) {
      id = obj.searchParams.get("v"); // Get ID from searchParam
      return id.length == 11 ? id : false;
    } else if (obj.pathname.startsWith("/embed/")) {
      try {
        return obj.pathname.substr(7, 11);
      } catch (e) {
        console.error("[SB] Video ID not valid");
        return false;
      }
    }
}

//returns the start time of the video if there was one specified (ex. ?t=5s)
function getYouTubeVideoStartTime(url) {
  let searchParams = new URL(url).searchParams;
  var startTime = searchParams.get("t");
  if (startTime == null) {
    startTime = searchParams.get("time_continue");
  }

  return startTime;
}