groton-school / knowledgebase

Knowledgebase website
https://kb.groton.org
GNU General Public License v3.0
0 stars 0 forks source link

Clean up YouTube embeds #1

Closed github-actions[bot] closed 1 year ago

github-actions[bot] commented 1 year ago

https://api.github.com/groton-school/knowledgebase/blob/944f9d24a27c9e3eb472eaeb3b734e6fc9472c3d/src/embed-youtube-links.js#L1


// FIXME YouTube is no longer embedding

const waitFor = (selector) => {
  return new Promise((resolve) => {
    if (document.querySelector(selector)) {
      return resolve(document.querySelector(selector));
    }

    const observer = new MutationObserver((mutations) => {
      if (document.querySelector(selector)) {
        resolve(document.querySelector(selector));
        observer.disconnect();
      }
    });

    observer.observe(document.body, {
      childList: true,
      subtree: true
    });
  });
};

waitFor('.CMSgoogledocembed').then((embed) => {
  Array.from(embed.querySelectorAll('a[href^="https://youtu"]')).forEach(
    (link) => {
      const id = link.href.replace(
        /^https:\/\/(?:youtu\.be)|(?:(?:www\.)?youtube\.com\/watch\?v=)\/(.+)\/?/,
        '$1'
      );
      link.outerHTML = `<iframe width="560" height="315" src="https://www.youtube-nocookie.com/embed/${id}" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>`;
    }
  );
});
battis commented 1 year ago

Wasn't a bug. It's that I had forgotten to embed the pages (framed pages don't work because of DOM and XSS security, of course).

Meanwhile this does need to catch instances where the YouTube links is followed or preceded by a thumbnail in the document, and hide that thumbnail when the video is embedded.