YouTube JS API seek

This commit is contained in:
polv committed 2026-09-23 21:05:12 +07:00
1 parent 218ba874f9
commit d9777c3c82
6 files changed
+99 -12

No files matched your search

+8 -5
View File
@@ -1,7 +1,7 @@
<template>
<Teleport to="body">
<div :class="$style.container">
<YouTube v-if="youtubeID" :id="youtubeID" />
<YouTube ref="yt" v-if="youtubeID" :id="youtubeID" />
<video
v-else-if="videoURL"
controls
@@ -21,6 +21,7 @@ import YouTube from "./YouTube.vue";
const { frontmatter } = useData<{ video?: string }>();
const videoURL = computed(() => frontmatter.value?.video);
const videoEl = useTemplateRef("video");
const ytEl = useTemplateRef("yt");
const youtubeID = ref("");
@@ -41,14 +42,15 @@ function imgClickListener(ev: PointerEvent) {
if (!(ev.target instanceof HTMLImageElement)) return;
const img = ev.target;
if (!videoEl.value) return;
const v = videoEl.value;
const [, min, sec] = /^(\d+)\:(\d+)$/.exec(img.alt) || [];
const t = min && sec ? parseInt(min) * 60 + parseInt(sec) : null;
if (!t) return;
v.currentTime = t;
if (videoEl.value) {
videoEl.value.currentTime = t;
} else if (ytEl.value) {
ytEl.value.seekTo(t);
}
}
watch(videoURL, () => {
@@ -59,6 +61,7 @@ function onVideoNotFound() {
const m = /\[(.+?)\]\.\S+$/.exec(videoURL.value || "") || [];
youtubeID.value = m[1] || "";
}
onVideoNotFound();
//@ts-ignore
const { SSR } = import.meta.env;
+25 -2
View File
@@ -1,10 +1,11 @@
<template>
<div :class="$style.container">
<iframe
id="yt-player"
:class="$style.iframe"
width="100%"
height="100%"
:src="'https://www.youtube.com/embed/' + $props.id"
:src="url.href"
frameborder="0"
allow="
accelerometer;
@@ -20,7 +21,29 @@
</template>
<script setup lang="ts">
defineProps<{ id: string; title?: string }>();
import { onMounted, ref } from "vue";
const props = defineProps<{ id: string; title?: string }>();
defineExpose({ seekTo });
const url = new URL("https://www.youtube.com/embed/" + props.id);
url.searchParams.set("enablejsapi", "1");
const player = ref();
onMounted(() => {
const { YT } = window as any;
if (YT?.Player) {
player.value = new YT.Player("yt-player");
}
});
function seekTo(t: number) {
if (player.value) {
player.value.seekTo(t, true);
}
}
</script>
<style module>