Restore YouTube Previews in Element

tl;dr: use the userscript I modified to show preview images (or the original by ItsCinnabar)

Recently, YouTube and Google have been showing modal cookie consent agreement forms when not logged on. This is slightly irksome if you don’t like browsing logged in to YT/Google. It has another effect: it breaks URL previews in Element, the Matrix chat client:

Not useful!

There’s a workaround for this on the individual client side: a userscript by ItsCinnabar. It’s useful, but it left the YouTube logo; not a big deal but I like having the image preview of the video more than I realised. So I forked the gist with one that uses the YT preview image specified in the <meta content='og:image'> element.


The Gist of the userscript to restore previews can be found here (or RAW for adding straight to a userscript manager), or copy and pasted from below. Enjoy!

// ==UserScript==
// @name         Element youtube preview
// @namespace
// @version      0.2
// @description  fix the embeds!!
// @author       Cinnabar (bertieb for images)
// @match
// @icon         data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==
// @grant        GM.xmlHttpRequest
// @connect
// @connect
// ==/UserScript==

(function() {
    'use strict';
    function previewEditor() {
        // const allPreviews = document.getElementsByClassName('mx_LinkPreviewWidget_caption');
        const allPreviews = document.getElementsByClassName('mx_LinkPreviewWidget');
        for (const preview of allPreviews) {
            const previewImg = preview.childNodes[0].children[0];
            const caption = preview.childNodes[1];
            const linkTitle = caption.childNodes[0].children[0];
            const linkDesc = caption.childNodes[2]
            if (linkTitle.text != "Before you continue to YouTube") {
                method: "GET",
                url: linkTitle.href,
                onload: function(response) {
                    if (response.status == 200){
                        const title = response.responseText.match(/<title[^>]*>([^<]+)<\/title>/)[1];
                        const desc = response.responseText.match(/<meta name="description" content="(.*?)">/)[1];
                        const imgsrc = response.responseText.match(/<meta property="og:image" content="(.*?)">/)[1];
                        linkTitle.text = title
                        linkDesc.textContent = desc
                        previewImg.src = imgsrc;

Tell us what's on your mind