Embed video from URL into note?

Hey all!
I was wondering if it’s possible to embed a video from an url into a card. I tried grabbing the video selector and url but I only get the stills. Currently I’m using this to fetch images from GettyImages (thanks @kleinerpirat !)

<span class="image-container" id="getty-image"></span>
<script>
function getRandom(arr, n) {
    var result = new Array(n),
        len = arr.length,
        taken = new Array(len)
        while (n--) {
            var x = Math.floor(Math.random() * len)
            result[n] = arr[x in taken ? taken[x] : x]
            taken[x] = --len in taken ? taken[len] : len
        }
    return result
}

var sites = [

   {
      name: "getty",
      url: "https://www.gettyimages.com/fotos/bar?assettype=image&phrase={{English}}",
      selector: "article > a > figure > picture > img",
      amount: 5,
      random: true
}
]

function scrapeImages(content, site) {

   let container = document.createElement("div")
   container.innerHTML = content
   let imageList = container.querySelectorAll(site.selector)
   let images = Array.from(imageList)

   let selected = (site.random ? getRandom(images.slice(0, 20), site.amount) : images.slice(0, site.amount))
   for (img of selected)  {
      img.parentNode.removeChild(img)
      document.getElementById(site.name + "-image").appendChild(img)
   }
}

function fetchHTML(site) {
   // pull content from page via API to avoid Same-origin policy
   fetch(`https://api.allorigins.win/get?url=${encodeURIComponent(site.url)}`)
      .then(response => {
         if (response.ok) return response.json()
         throw new Error('Network response was not ok.')
      })
      .then(data => scrapeImages(data.contents, site))
}

// Initiate search
for (site of sites) {
   fetchHTML(site)
}
</script>

Not all YouTube videos allow embedding, but you should be able to embed a lot of videos with the following script. Because YouTube URLs come in many different forms, I have chosen to rely on the <a> tag that’s automatically generated by Anki rather than going for a pure RegEx solution.

So provided your links show up in blue (meaning they’re wrapped in <a> within Anki) and the video creator allowed embedding, this script enables you to embed an arbitrary number of YouTube videos (like the image scraping script I wrote for you back then) from a single field.

To start at a specific time, just right-click a video and select “Copy video URL at current time”, then paste it into a field called “YouTube”.

Back template

<div id="yt">{{YouTube}}</div>

<script>
 /**
 * Embed arbitrary number of YouTube videos
 * - requires an element with id="yt"
 * - only works with actual links: <a>
 * 
 * @author Matthias Metelka (kleinerpirat)
 */
  function embedYouTube() {
    const yt = document.getElementById("yt");
    const anchors = yt.querySelectorAll("a");
    const idRegex = /(?:.*?)(?:^|\/|v=)([A-Za-z0-9_-]{11})(?:.*)?/;
    const timeRegex = /[&?#]?t=(\d+[smh]?)+/;

    const attrs = {
      title: "youtube",
      id: "yt-iframe",
      loading: "lazy",
      frameborder: "0",
      allow:
        "accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture",
      allowfullscreen: "true",
    };

    const gallery = document.createElement("div");
    gallery.className = "yt-gallery";

    for (let a of anchors) {
      const data = {
        id: idRegex.exec(a.href)?.[1] || null,
        time: `?start=${timeRegex.exec(a.href)?.[1] || "0"}`,
      };
      if (data.id) {
        const iframe = document.createElement("iframe");
        Object.keys(attrs).forEach((key) => {
          iframe.setAttribute(key, attrs[key]);
        });
        iframe.src = `https://www.youtube-nocookie.com/embed/${data.id}${data.time}`;
        const container = document.createElement("div");
        container.className = "yt-container";
        container.appendChild(iframe);
        gallery.appendChild(container);
      }
    }
    yt.innerHTML = "";
    yt.appendChild(gallery);
  }

  (() => {
    if (globalThis.onUpdateHook) {
      onUpdateHook.push(embedYouTube);
    } else setTimeout(() => embedYouTube());
  })();
</script>

Recommended CSS

.yt-container {
  margin-top: 1em;
  position: relative;
  padding-bottom: 56.25%;
  padding-top: 0;
  height: 0;
  overflow: hidden;
}
.yt-container > iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
2 Likes

Hi, I can embed any YouTube video using an iframe, but I can’t embed this video from Loom, can you give me some hints please?

<div style="position: relative; padding-bottom: 61.224489795918366%; height: 0;"><iframe src="https://www.loom.com/embed/5bbdeb480ba84e65b1b3de8c190e2003" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;"></iframe></div>