YouTube timecode support for embeds

I enter a lot of YouTube links with a timecode included in the url, for example, a YouTube url that ends with “?t=1160” or something similar. The embed that is displayed does not respect the timecode, but instead, starts playing at the beginning of the video. Embedded YouTube videos do support a start time too. Could we have that for Logseq’s editor as well? (See Embed videos & playlists - YouTube Help)

It works to me. Could you share a URL that doesn’t work?

For example, this one: https://youtu.be/H_fKmD-Ntnk?t=206

(I created it by right-clicking a YouTube video, and selecting “Copy video URL at current time”.)

  • Ok, it works but in this format: https://www.youtube.com/watch?v=H_fKmD-Ntnk&t=206s
  • Would you be interested in some custom javascript that automatically detects the different format and converts it to the working one?
2 Likes

Ok, good to know.

Yeah, why not, thanks!

Add the following code into file custom.js :

const iframes = document.getElementsByTagName("iframe");
const iframesObserver = new MutationObserver(function onMutated(){
    Array.prototype.map.call(iframes, (iframe)=>{
        const id = iframe.id
        if (!id.startsWith("youtube")) return

        const parent = iframe.closest(".ls-block")
        const uuid = parent.querySelector(".block-content").getAttribute("blockid")
        const block = logseq.api.get_block(uuid)
        const old = block.content
        const i = old.indexOf("?t=")
        if (i < 0) return

        const content = old.slice(0, 16) + "www.youtube.com/watch?v=" + old.slice(25, i) + "&" + old. slice(i + 1)
        logseq.api.update_block(uuid, content)
    })
});
iframesObserver.observe(document.getElementById("app-container"), {
    attributes: true,
    subtree: true,
    attributeFilter: ["class"]
});
  • This assumes that the block contains nothing else but a pasted link.
1 Like

Thank you for this! I’ll give it a go.