Enable JS API on Youtube Embeds

Created on 17 June 2020, over 4 years ago
Updated 18 January 2024, 11 months ago

I have a use case wherein I need to access to YouTube's iframe api for analytics purposes. In order to do so my embed links need to have "enablejsapi=1" attached as a query param to the embed src. I'll work on a patch.

✨ Feature request
Status

Closed: won't fix

Version

2.4

Component

Video Embed Field (base module)

Created by

πŸ‡ΊπŸ‡ΈUnited States jcourtice Kansas City, MO

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

  • πŸ‡ΊπŸ‡ΈUnited States bburg Washington D.C.

    The hook in the previous example doesn't work, in Drupal 10.1 at least, because the $variables['media'] variable shouldn't be a string. It should be an IFrameMarkup object. Setting it as a string like in the previous comment causes the embed to render as plain text markup, which is visible on the page. Instead, create a new object, with the value of the replaced string.

    function hook_preprocess_media_oembed_iframe(array &$variables) {
      $resource = $variables['resource'];
      if ($resource->getProvider()->getName() === 'YouTube') {
        // We are rendering a YouTube video, so modify the URL of the video so that it only shows related videos from the same channel.
        // The video's markup is only available as a string, so we need to use str_replace() to modify the URL.
         $new_string = str_replace('?feature=oembed', '?feature=oembed&enablejsapi=1', (string) $variables['media']);
         $new_media = $variables['media']::create($new_string);
         $variables['media'] = $new_media;
      }
    }
    
Production build 0.71.5 2024