onYouTubeIframeAPIReady function is not calling

2019-06-04 04:11发布

I want to call onYouTubeIframeAPIReady function but this is not firing. I am getting only frameID in console but other functions are not getting called.

$(document).ready(function(){
    var player;
    var ytsrc = $('.video_holder_frame').find('iframe').attr('src');
    if (ytsrc) ytsrc = ytsrc.match(/youtube.com\/embed\/([^\\?]*)/i);
    if (!ytsrc) return;
    var frameID = 'youtube_' + ytsrc[1];    
    console.log(frameID);
    $('.video_holder_frame').find('iframe').attr('id', frameID);

    function attachToYoutubeFrame() {
        console.log("attachToYoutubeFrame");
        function onytplayerStateChange(newState) {
            console.log("onytplayerStateChange");
            console.log(newState);
        };

        player = new YT.Player(frameID, {
            events: {
                "onStateChange": onytplayerStateChange
            }
        });
    };

    function onYouTubeIframeAPIReady() {
        attachToYoutubeFrame();
    };
});

2条回答
唯我独甜
2楼-- · 2019-06-04 04:22

If anyone one is struggling here this is the one that solves it...

Add - Because calling it in your script causes issues

Also, make sure your using - window.onYouTubeIframeAPIReady = function() {

Those two things fixed two days of anger.

查看更多
何必那么认真
3楼-- · 2019-06-04 04:40

Your onYouTubeIframeAPIReady() function must be defined globaly. Simply replace the line

function onYouTubeIframeAPIReady() {

with

window.onYouTubeIframeAPIReady = function() {

It is also important to load the youtube iframe api library file:

<script type="text/javascript" src="https://www.youtube.com/iframe_api"></script>

Also your iframe src url must have appended the enablejsapi=1 parameter:

http://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1
查看更多
登录 后发表回答