YouTube iframe API: how do I control an iframe player that's already in the HTML?

前端 未结 5 1417
[愿得一人]
[愿得一人] 2020-11-22 08:00

I want to be able to control iframe based YouTube players. This players will be already in the HTML, but I want to control them via the JavaScript API.

I\'ve been re

5条回答
  •  醉梦人生
    2020-11-22 08:39

    You can do this with far less code:

    function callPlayer(func, args) {
        var i = 0,
            iframes = document.getElementsByTagName('iframe'),
            src = '';
        for (i = 0; i < iframes.length; i += 1) {
            src = iframes[i].getAttribute('src');
            if (src && src.indexOf('youtube.com/embed') !== -1) {
                iframes[i].contentWindow.postMessage(JSON.stringify({
                    'event': 'command',
                    'func': func,
                    'args': args || []
                }), '*');
            }
        }
    }
    

    Working example: http://jsfiddle.net/kmturley/g6P5H/296/

提交回复
热议问题