首页 > 解决方案 > 访问 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>

标签: javascriptjqueryiframeyoutube-iframe-api

解决方案


使用 iFrame 时的简单规则是,只有当它从同一主机/源提供时,您才能访问其中的内容。

这是所有浏览器在安全方面的标准行为。底线,如果来自不同域,则无法直接访问 iFrame 的内容。

在这种情况下,我看到的唯一解决方案是,由于您使用 Youtube API 创建,只需将您创建的播放器对象缓存到 var,然后在控制台中探索其中的方法


推荐阅读