Embed Links - Modify width and height of the embed

I cannot adjust the width and height of an embed field in which I'm pasting a YouTube Link.
The only prop available for PrismicEmbed is the field prop.

I've also tried using the {@html slice.primary.embed.html} but that doesn't work, as I'm then unable to set the width and height.

I also tried to set the width and height directly in the javascript part of the svelte component yet no luck.

Help please.

Hi @aadtyaraj01 ,

These previous threads should help:

Thanks.

1 Like

So for now I'm relying on this snippet to replace the width and height values:

/**
 * Resizes the width and height attributes of an iframe in an HTML string.
 *
 * @param {string} html - The original HTML string containing the iframe.
 * @param {number} newWidth - The new width to set for the iframe.
 * @param {number} newHeight - The new height to set for the iframe.
 * @returns {string} The modified HTML string with updated width and height.
 *
 * @example <caption>Resize a YouTube embed iframe</caption>
 * {@lang javascript}
 * const originalHtml = '<iframe width="200" height="113" src="https://www.youtube.com/embed/gBrmnB5aOSI" frameborder="0" allowfullscreen></iframe>';
 * const resizedHtml = resizeVideoIframe(originalHtml, 400, 225);
 * console.log(resizedHtml);
 * // Output: '<iframe width="400" height="225" src="https://www.youtube.com/embed/gBrmnB5aOSI" frameborder="0" allowfullscreen></iframe>'
 */
function resizeVideoIframe(html, newWidth, newHeight) {
	// Use regular expressions to replace width and height
	const patternWidth = /width="\d+"/;
	const patternHeight = /height="\d+"/;

	// Replace width
	html = html.replace(patternWidth, `width="${newWidth}"`);

	// Replace height
	html = html.replace(patternHeight, `height="${newHeight}"`);

	return html;
}

1 Like

For reference, here's a way to do it with simple CSS:

Hi @aadtyaraj01
Here is my own solution using a custom RichText component

.iframe {
  margin-block: 3.12rem;
  width: 100% !important;
  overflow-y: hidden;

  & iframe {
    width: 100% !important;
    height: inherit !important;
  }
}
const reconstructEmbedUrl = (originalUrlString) => {
  if (!originalUrlString) {
    return originalUrlString;
  }

  try {
    const tempUrl = new URL(originalUrlString);
    const hostname = tempUrl.hostname.toLowerCase();
    const pathname = tempUrl.pathname;

    if (hostname.includes('youtube.com') || hostname.includes('youtu.be')) {
      let videoId = null;
      if (hostname.includes('youtu.be')) {
        videoId = pathname.substring(1);
      } else if (pathname.includes('/watch')) {
        videoId = tempUrl.searchParams.get('v');
      } else if (pathname.includes('/embed/')) {
        videoId = pathname.split('/embed/')[1]?.split('/')[0];
      }

      if (videoId) {
        const embedUrl = new URL(`https://www.youtube.com/embed/${videoId}`);
        embedUrl.searchParams.set('rel', '0');
        if (tempUrl.searchParams.has('t')) {
          embedUrl.searchParams.set(
            'start',
            tempUrl.searchParams.get('t').replace('s', ''),
          );
        }
        return embedUrl.toString();
      }
    }

    if (hostname.includes('vimeo.com')) {
      const pathParts = pathname.split('/');
      const videoId = pathParts.pop() || pathParts.pop();

      if (videoId && /^\d+$/.test(videoId)) {
        if (
          hostname.includes('player.vimeo.com') &&
          pathname.includes('/video/')
        ) {
          return originalUrlString;
        }
        return `https://player.vimeo.com/video/${videoId}`;
      }
    }
  } catch (e) {
    return originalUrlString;
  }

  return originalUrlString;
};
 embed: ({node}) => {
    let url;
    let customHeight;

    try {
      const initialEmbedUrlString = node.oembed?.embed_url;
      if (
        !initialEmbedUrlString ||
        typeof initialEmbedUrlString !== 'string' ||
        initialEmbedUrlString.trim() === ''
      ) {
        console.log('Embed URL string is invalid, returning null.');
        return null;
      }

      const reconstructedEmbedUrlString = reconstructEmbedUrl(
        initialEmbedUrlString,
      );

      url = new URL(reconstructedEmbedUrlString);
      customHeight = url.searchParams.get('height');

      if (customHeight) {
        url.searchParams.delete('height');
      }
    } catch (error) {
      console.error(
        'Error processing embed URL:',
        node.oembed?.embed_url,
        error,
      );
      return null;
    }

    if (!node.oembed) {
      console.error('Missing oembed data for node, returning null:', node);
      return null;
    }

    if (node.oembed.html) {
      //  PrismicRichText might render this HTML directly, ignoring the custom iframe structure below. Attempting to wrap it.',
      return (
        <div
          className={styles.iframe}
          style={{
            height: customHeight ? `${customHeight}px` : 400,
            position: 'relative',
            width: '100%',
          }}
          dangerouslySetInnerHTML={{__html: node.oembed.html}}
        />
      );
    }

    return (
      <div
        className={styles.iframe}
        style={{
          height: customHeight ? `${customHeight}px` : undefined,
          position: 'relative',
          width: '100%',
        }}
      >
        <iframe
          style={{
            position: !customHeight ? 'absolute' : undefined,
            top: !customHeight ? 0 : undefined,
            left: !customHeight ? 0 : undefined,
            width: '100% !important',
            height: customHeight
              ? `${customHeight}px`
              : !customHeight
                ? '100%'
                : 230,
          }}
          src={url.toString()}
          title={node.oembed.title || 'Embedded content'}
          data-oembed={node.oembed.embed_url}
          data-oembed-type={node.oembed.type}
          data-oembed-provider={node.oembed.provider_name}
          frameBorder='0'
          allowFullScreen
          loading='lazy'
        />
      </div>
    );
  },
1 Like