Render YouTube start time GET variable when rendering Remote Video

Created on 27 February 2024, 10 months ago

I've been tinkering with hook_preprocess_media_oembed_iframe() for a bit and only just realized that the GET variable for the video start time had not been included.

I know there's various ways of achieving this from the field value in Twig, as I've done this in the past, such as simply using the raw source URL from the entity reference and rendering an iframe directly.

I'd much prefer to use the built-in rendering for this, but the big hangup lies in the start time GET variable. The only GET variable attached pre-render seems to be the feature=oembed parameter.

Below is my current usage of the aforementioned hook. Is there anything I can do here to retrieve the parameter from the referenced entity?

function mytheme_preprocess_media_oembed_iframe(array &$variables) {
  /** @var \Drupal\media\OEmbed\Resource $resource */
  $resource = $variables['resource'];

  if ($resource->getProvider()->getName() === 'YouTube') {
    // Construct a DOMDocument from the given iframe markup.
    $dom = Html::load((string) $variables['media']);

    /** @var \DOMElement $iframe */
    $iframe = $dom->getElementsByTagName('iframe')->item(0);

    // Remove superfluous attributes.
    $iframe->removeAttribute('allow');
    $iframe->removeAttribute('allowfullscreen');

    // Allow for the iframe to be lazy loaded.
    $iframe->setAttribute('loading', 'lazy');

    // Alter the iframe src attribute,
    $iframe_src = $iframe->getAttribute('src');
    $iframe_src = str_replace('www.youtube.com', 'www.youtube-nocookie.com', $iframe_src);

    // Append the start time parameter...

    $iframe->setAttribute('src', $iframe_src);

    // Replace the media with the altered markup.
    $variables['media'] = Html::serialize($dom);
  }
}
πŸ’¬ Support request
Status

Active

Version

10.2 ✨

Component
MediaΒ  β†’

Last updated about 1 hour ago

Created by

πŸ‡ΊπŸ‡ΈUnited States FrankieD3

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

Comments & Activities

Production build 0.71.5 2024