无法直接获取跨域iframe内视频进度,因同源策略强制拦截;仅同源或第三方提供postmessage api(如youtube)时可行,且需严格遵循其通信规范。

iframe内视频进度无法直接获取,除非同源且对方提供API
浏览器的同源策略(Same-Origin Policy)会阻止父页面读取iframe内部的 DOM 或 JS 状态。如果视频嵌在第三方平台(比如 YouTube、Bilibili、腾讯视频),你根本拿不到video元素,更别说currentTime或duration。
可行的前提只有两个:① iframe 页面与父页同源(例如都是https://example.com下);② 对方明确暴露了可调用的 postMessage 接口,且你已按规范监听和响应。
- YouTube 提供了
postMessageAPI:需先用player.getCurrentTime(),但必须等onReady事件后才能调用 - Bilibili 嵌入播放器不开放进度查询,官方未提供对应 message 接口
- 自建同源视频页可直接访问
iframe.contentDocument.querySelector('video').currentTime
YouTube iframe如何安全获取播放进度
YouTube 是少数明确支持进度查询的第三方服务,但必须走它的 postMessage 流程,不能绕过。
关键步骤:
- 初始化 iframe 时必须添加
?enablejsapi=1&origin=https%3A%2F%2Fyourdomain.com参数(origin必须精确匹配父页协议+域名) - 监听
message事件,过滤来源为https://www.youtube.com,再解析event.data是否为{ "event": "infoDelivery", "info": { "currentTime": 12.5 } } - 主动请求进度需发
postMessage('{ "event": "command", "func": "getCurrentTime", "args": [] }', 'https://www.youtube.com') - 首次通信前,要等
onYouTubeIframeAPIReady回调触发,否则postMessage会被忽略
跨域 iframe里video元素的currentTime为什么读不到
不是代码写错了,是浏览器强制拦截。哪怕你写了 iframe.contentWindow.document.querySelector('video').currentTime,也会立刻抛出 DOMException: Blocked a frame with origin ... from accessing a cross-origin frame. 错误。
这个限制无法通过 CORS、document.domain 或 CSP 绕过 —— 它是渲染进程级隔离,和 HTTP 头无关。
- Chrome / Firefox / Safari 全部严格执行,无例外
-
iframe.sandbox属性若没加allow-scripts,连postMessage都发不出去 - 即使 iframe 内 JS 主动把
currentTime传出来,也得依赖对方配合发送postMessage,否则就是单向阻断
同源iframe中直接读取video进度的最小可行代码
仅适用于你自己控制的 iframe 页面(例如 /player.html 和父页同域)。
<iframe id="video-frame" src="/player.html"></iframe>
<script>
const iframe = document.getElementById('video-frame');
iframe.onload = () => {
const video = iframe.contentDocument.querySelector('video');
console.log(video.currentTime); // ✅ 可读
video.addEventListener('timeupdate', () => {
console.log('当前进度:', video.currentTime);
});
};
</script>
注意:iframe.onload 必须等待,否则 contentDocument 可能为空;若 iframe 使用 srcdoc,则无需 onload,但需确保内联 HTML 已含 video 标签。
真正难的从来不是怎么写这一行代码,而是确认那个 iframe 是否真的允许你碰它的内部状态 —— 大部分时候,答案是否定的。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











