Skip to content

How to embed a youtube video? #387

@amo13

Description

@amo13

After lots of trying, I have failed at embedding a youtube video. I don't understand how to add the HTML to what lexxy renders in the end.

Here is my attempt. I paste a link to a youtube video in the editor and it gets replaced by the video embedding. Perfect so far. But when I hit save and view the result of what is being rendered, I only get empty lines, or more precisely:

<figure class="attachment attachment--content">
  "\n      <div class="\&quot;youtube-embed-wrapper\&quot;">\n        \n        \n      </div>\n    "

</figure>

This is my stimulus controller:

import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  connect() {
    this.element.addEventListener("lexxy:insert-link", this.handleLinkInsert.bind(this))
  }

  disconnect() {
    this.element.removeEventListener("lexxy:insert-link", this.handleLinkInsert.bind(this))
  }

  handleLinkInsert(event) {
    const url = event.detail.url
    const videoId = this.extractVideoId(url)
    
    if (videoId) {
      const embedHtml = this.generateEmbedHtml(videoId)
      event.detail.replaceLinkWith(embedHtml, { attachment: true })
    }
  }

  extractVideoId(url) {
    const patterns = [
      // Handle v= parameter anywhere in query string for youtube.com URLs
      /youtube\.com\/watch.*[?&]v=([^&\n?#]+)/,
      // Handle youtu.be format
      /youtu\.be\/([^&\n?#]+)/,
      // Handle embed format
      /youtube\.com\/embed\/([^&\n?#]+)/,
      // Handle v/ format
      /youtube\.com\/v\/([^&\n?#]+)/
    ]

    for (const pattern of patterns) {
      const match = url.match(pattern)
      if (match) {
        return match[1]
      }
    }

    return null
  }

  generateEmbedHtml(videoId) {
    return `
      <div class="youtube-embed-wrapper">
        <iframe 
          width="560" 
          height="315" 
          src="https://www.youtube-nocookie.com/embed/${videoId}" 
          title="YouTube video player" 
          frameborder="0" 
          allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" 
          referrerpolicy="strict-origin-when-cross-origin" 
          allowfullscreen>
        </iframe>
      </div>
    `
  }
}

I am pretty sure I am doing something wrong here, but I need help in figuring out what and how I should go about embedding a youtube video.

I'd be thankful for any advice.


Edit: If I set attachment: false instead of true, nothing appears to happen at all after pasting the link into the editor. No link appears, but no embedded video either.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions