Skip to content

Commit

Permalink
Make YoutubeLinkEnhancement URL parsing more robust.
Browse files Browse the repository at this point in the history
[URL API] `searchParams` works in all browsers as of 2017. It also
considerably simplifies the code and makes the intent much clearer.

Resolves
https://github.com/alphagov/govuk_publishing_components/security/code-scanning/1

[URL API]: https://developer.mozilla.org/en-US/docs/Web/API/URL
  • Loading branch information
sengi committed Apr 30, 2024
1 parent db67015 commit 4621243
Showing 1 changed file with 10 additions and 17 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
}
}

if (href.indexOf('/live_stream') >= 0) {
if (href.includes('/live_stream')) {
var channelId = YoutubeLinkEnhancement.parseLivestream(href)

if (!this.hasDisabledEmbed($link) && channelId) {
Expand Down Expand Up @@ -195,23 +195,16 @@
// This is a public class method so it can be used outside of this embed to
// check that user input for videos will be supported in govspeak
YoutubeLinkEnhancement.parseVideoId = function (url) {
var parts
var u

if (url.indexOf('youtube.com') > -1) {
var params = {}
parts = url.split('?')
if (parts.length === 1) {
return
}
parts = parts[1].split('&')
for (var i = 0; i < parts.length; i++) {
var part = parts[i].split('=')
params[part[0]] = part[1]
}
return params.v
} else if (url.indexOf('youtu.be') > -1) {
parts = url.split('/')
return parts.pop()
try {
u = new URL(url)
} catch (e) { return }

if (u.host === 'www.youtube.com' || u.host === 'youtube.com') {
return u.searchParams.get('v')
} else if (u.host === 'youtu.be') {
return u.pathname.slice(1) // Trim the leading /
}
}

Expand Down

0 comments on commit 4621243

Please sign in to comment.