SORU
16 EYLÜL 2011, Cuma


İframe API YouTube: nasıl'ın bu iframe çalar denetim zaten HTML yapabilirim?

İframe tabanlı YouTube oyuncuları kontrol edebilmek istiyorum. Bu oyuncular zaten HTML, JavaScript ile kontrol etmek istiyorum.

API ile sayfa için yeni bir video eklemek için nasıl açıklamak, ve sonra da onu kontrol YouTube player ile işlevleri: documentation for the iframe API okuyordum

var player;
function onYouTubePlayerAPIReady() {
    player = new YT.Player('container', {
        height: '390',
        width: '640',
        videoId: 'u1zgFlCw8Aw',
        events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
        }
    });
}

Kodu yeni oyuncu bir nesne oluşturur ve atar. o zaman içinde ekler #kap div. oyuncu Sonra 'oyuncu' ve*, pauseVideo(), *5 çağrı vb. ameliyat edebilirim bunun üzerine.

Ama zaten sayfada olan iframe oyuncular üzerinde çalıştırmak için güçlü olmak istiyorum.

Bu çok kolay gibi bir şey ile eski embed yöntemi ile yapabilirim:

player = getElementById('whateverID');
player.playVideo();

Ama bu yeni iframe çalışmıyor. Nasıl zaten sayfada iframe nesnesi atamak ve API fonksiyonlarını kullanabilir miyim?

CEVAP
22 EYLÜL 2011, PERŞEMBE


Keman Bağlantılar: Source code - Preview - Small versionListening for Youtube Event in jQuery

Derin bir kod sonucu analizi, fonksiyon oluşturdum: bir fonksiyon herhangi bir çerçeveli YouTube video çağrısı function callPlayer istekleri. YouTube Api reference Olası işlev çağrıları tam bir listesini almak için. Açıklama için kaynak kodu yorumlarını okuyabilirsiniz.

17 Mayıs 2012, boyut oyuncunun hazır durumuna dikkat çekmek amacıyla iki katına çıkaran kod. Eğer oyuncunun hazır devlet ile anlaşma değil, kompakt bir işlevi gerekiyorsa, http://jsfiddle.net/8R5y6/ bkz.

/**
 * @author       Rob W <gwnRob@gmail.com>
 * @website      http://stackoverflow.com/a/7513356/938089
 * @version      20131010
 * @description  Executes function on a framed YouTube video (see website link)
 *               For a full list of possible functions, see:
 *               https://developers.google.com/youtube/js_api_reference
 * @param String frame_id The id of (the div containing) the frame
 * @param String func     Desired function to call, eg. "playVideo"
 *        (Function)      Function to call when the player is ready.
 * @param Array  args     (optional) List of arguments to pass to function func*/
function callPlayer(frame_id, func, args) {
    if (window.jQuery && frame_id instanceof jQuery) frame_id = frame_id.get(0).id;
    var iframe = document.getElementById(frame_id);
    if (iframe && iframe.tagName.toUpperCase() != 'IFRAME') {
        iframe = iframe.getElementsByTagName('iframe')[0];
    }

    // When the player is not ready yet, add the event to a queue
    // Each frame_id is associated with an own queue.
    // Each queue has three possible states:
    //  undefined = uninitialised / array = queue / 0 = ready
    if (!callPlayer.queue) callPlayer.queue = {};
    var queue = callPlayer.queue[frame_id],
        domReady = document.readyState == 'complete';

    if (domReady && !iframe) {
        // DOM is ready and iframe does not exist. Log a message
        window.console && console.log('callPlayer: Frame not found; id='   frame_id);
        if (queue) clearInterval(queue.poller);
    } else if (func === 'listening') {
        // Sending the "listener" message to the frame, to request status updates
        if (iframe && iframe.contentWindow) {
            func = '{"event":"listening","id":'   JSON.stringify('' frame_id)   '}';
            iframe.contentWindow.postMessage(func, '*');
        }
    } else if (!domReady ||
               iframe && (!iframe.contentWindow || queue && !queue.ready) ||
               (!queue || !queue.ready) && typeof func === 'function') {
        if (!queue) queue = callPlayer.queue[frame_id] = [];
        queue.push([func, args]);
        if (!('poller' in queue)) {
            // keep polling until the document and frame is ready
            queue.poller = setInterval(function() {
                callPlayer(frame_id, 'listening');
            }, 250);
            // Add a global "message" event listener, to catch status updates:
            messageEvent(1, function runOnceReady(e) {
                if (!iframe) {
                    iframe = document.getElementById(frame_id);
                    if (!iframe) return;
                    if (iframe.tagName.toUpperCase() != 'IFRAME') {
                        iframe = iframe.getElementsByTagName('iframe')[0];
                        if (!iframe) return;
                    }
                }
                if (e.source === iframe.contentWindow) {
                    // Assume that the player is ready if we receive a
                    // message from the iframe
                    clearInterval(queue.poller);
                    queue.ready = true;
                    messageEvent(0, runOnceReady);
                    // .. and release the queue:
                    while (tmp = queue.shift()) {
                        callPlayer(frame_id, tmp[0], tmp[1]);
                    }
                }
            }, false);
        }
    } else if (iframe && iframe.contentWindow) {
        // When a function is supplied, just call it (like "onYouTubePlayerReady")
        if (func.call) return func();
        // Frame exists, send message
        iframe.contentWindow.postMessage(JSON.stringify({
            "event": "command",
            "func": func,
            "args": args || [],
            "id": frame_id
        }), "*");
    }
    /* IE8 does not support addEventListener... */
    function messageEvent(add, listener) {
        var w3 = add ? window.addEventListener : window.removeEventListener;
        w3 ?
            w3('message', listener, !1)
        :
            (add ? window.attachEvent : window.detachEvent)('onmessage', listener);
    }
}

Kullanımı:

callPlayer("whateverID", function() {
    // This function runs once the player is ready ("onYouTubePlayerReady")
    callPlayer("whateverID", "playVideo");
});
// When the player is not ready yet, the function will be queued.
// When the iframe cannot be found, a message is logged in the console.
callPlayer("whateverID", "playVideo");

(Ve Cevaplar) Olası sorular:

S: Çalışmıyor!
Bir: "İşe yaramıyor" net bir açıklama değil. Herhangi bir hata iletisi alıyor musunuz? İlgili kodu göstermek lütfen.

S: YouTube video <iframe src="http://www.youtube.com/embed/As2rZGPGKDY" />kullanarak gömülü var ama işlevi herhangi bir fonksiyonu çalıştırmak için değil!
Bir: URL: sonunda ?enablejsapi=1 eklemek /embed/vid_id?enablejsapi=1.

S: Hata iletisi: "geçersiz veya geçersiz Bir dize belirtildi". Neden?
Bir: API düzgün yerel bir ana bilgisayar (file://) çalışmıyor. (Test) sayfa online Ana veya JSFiddle kullanın. Örnekler: bu cevap üst kısmındaki bağlantılara Bakın.

SBu nasıl biliyor musun?
Bir: El ile API kaynak yorumlamak için biraz zaman geçirdim. postMessage yöntemi kullanmam sonucuna vardım. Geçmek bilmek, mesajlar karşılar bir Chrome uzantısı oluşturdu. Uzantısı için kaynak kodu here indirilebilir.

S: Desteklenen tarayıcılar nelerdir?
Bir: JSON postMessage destekleyen her tarayıcı.

  • YANİ 8
  • Firefox 3.6 (aslında 3.5, ama document.readyState 3.6 uygulanmıştır)
  • Opera 10.50
  • Safari 4
  • Krom 3

İlgili cevap / uygulama: Fade-in a framed video using jQuery
Tam API desteği: Listening for Youtube Event in jQuery
Resmi API: https://developers.google.com/youtube/iframe_api_reference

Sürüm geçmişi

  • Mayıs 2012 17
    onYouTubePlayerReadyuygulanan: callPlayer('frame_id', function() { ... }).
    Fonksiyonları oyuncu henüz hazır değilken otomatik olarak sıraya alınmış.
  • Temmuz 2012 24
    Güncellenmiş ve successully desteklenen tarayıcılar (önüne bak) test.
  • 10 Ekim 2013 Bir işlev bağımsız değişken olarak geçirildiğinde, callPlayer hazır kontrol zorlar. Bu callPlayer belge hazır iken iframe ekleme hemen sonra çağrıldığında, iframe tam olarak hazır olduğundan emin olamaz, çünkü gerekli. Internet Explorer ve Firefox, bu senaryo göz ardı edildi postMessage, çok erken bir çağırma sonuçlandı.
  • 12 Aralık 2013, URL &origin=* eklemek için tavsiye.
  • 2 Mar 2014, tavsiye URL'YE &origin=* kaldırmak için geri çekildi.

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • ibebrent

    ibebrent

    23 Temmuz 2007
  • Paul Schroder

    Paul Schrode

    30 Kasım 2007
  • rekjavicxxx

    rekjavicxxx

    28 EKİM 2007