javascript - 访问 iFrame 中的元素
问题描述
我需要获取我在 iFrame 中播放的 youtube 视频的当前时间,但无法从我的脚本访问视频。
在浏览器开发工具中选择视频后,我可以console.alert($("#player").children[0].getCurrentTime())
毫无问题地使用。
但是,TypeError: Cannot read property 'getCurrentTime' of undefined
当从脚本运行相同的代码时,我会得到。
这篇关于 SO 的帖子让我觉得如果没有打开开发工具,这与隐藏的元素有关。然而$("#player").children[0].removeClass("hidden")
回报TypeError: $(...).contents is not a function at <anonymous>
。该元素似乎不存在。
下面是完整的代码,其中 90% 直接来自这里的第一个 iframe 示例。
<!DOCTYPE html>
<html>
<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'U03lLvhBzOw',
events: {
'onReady': onPlayerReady
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
console.alert($("#player").children[0].getCurrentTime()) //DOESN'T WORK
}
</script>
</body>
</html>
解决方案
使用 iFrame 时的简单规则是,只有当它从同一主机/源提供时,您才能访问其中的内容。
这是所有浏览器在安全方面的标准行为。底线,如果来自不同域,则无法直接访问 iFrame 的内容。
在这种情况下,我看到的唯一解决方案是,由于您使用 Youtube API 创建,只需将您创建的播放器对象缓存到 var,然后在控制台中探索其中的方法
推荐阅读
- uiviewcontroller - UIViewController生命周期破iOS13,makeKeyAndVisible()好像不能操作?
- matlab - 如何为 ltiview 添加标题?
- javascript - 获取异步/等待数据并在 html 中显示/返回
- c - 如何限制在c中运行的并发线程并在每个线程完成执行后获取它的返回值(pthread)
- cypress - 如何在赛普拉斯中使用 fakerjs
- amazon-s3 - 如何将 api gateway rest api 限制为 CloudFront 托管的 S3 网站
- django - 带有下划线的Django模型名称?
- python - Jupyter 实验室/笔记本曾经可以工作,但现在打开时崩溃或无法打开
- search - 使用 Lucene 查找术语出现超过一定次数的文档
- javascript - 获取 Javascript 数组的唯一值